2014-12-30 10 views
3

나는 경보 서비스를 사용했다. 1 분마다 실행되도록 알람을 구현했습니다. 따라서 앱이 종료 된 후에도 브로드 캐스트 리시버 onReceive 메소드가 호출됩니다. 이 onReceive 메서드 내부에 타이머를 구현하고 싶습니다. 위치 추적을 시작하고 20 초 후에 위치 추적을 중지해야합니다.앱이 종료 된 후에도 알람 수신기 내부에서 실행되는 타이머를 구현하는 방법은 무엇입니까?

나는 아래

TimerTask 
Handler 
Local Broadcast Receiver 

을 시도하지만 응용 프로그램이 종료되면 실행 위의 모든 할 수 없다.

알람 수신기 안에 20 초 동안 기다리는 타이머를 구현하고 싶습니다.
앱을 종료 할 때 어떻게해야합니까?

내 AlaramReceiver onReceive 방법 :

@Override 
public void onReceive(Context context, Intent intent) { 
    mContext = context; 
    mSharedPrefManager = SharedPrefManager.getInstance(mContext); 

    mAppUtilInstance.logDebugMessage(TAG, "Track interval alarm receiver."); 

    // // Check the preference having any current activity 
    if (mSharedPrefManager.checkForCurrentActivityPref()) { 
     userActivity = mSharedPrefManager.getCurrentUserActivityPref(); 

     if (mSharedPrefManager.getIsUserMovedPref()) { 
      // User MOVED 
      // Call the location service 
      LocationUpdateTimer locationUpdateTimer = new LocationUpdateTimer(
      mContext, userActivity, true); 
       locationUpdateTimer.initialize(); 
      mSharedPrefManager.setIsUserMovedPref(false); 
     } else { 
      // User not MOVED in between the track interval period. He is 
      // IDLE 
      // Check whether the location information is returned by the 
      // google API 
      if (mSharedPrefManager.checkForLocationEntityPref() 
        && mSharedPrefManager.getLocationEntityPref() 
          .getLatitude().length() > 0) { 
       // Send the packet information to the Fleetilla server 
       StoreAndSendLocationInformation storeAndSendLocationInformation = new StoreAndSendLocationInformation(
         mContext, 
         mSharedPrefManager.getLocationEntityPref(), 
         userActivity); 
       storeAndSendLocationInformation.storeAndSend(); 
      } else { 
       // If the location information is not available 
       mAppUtilInstance 
         .logDebugMessage(TAG, 
           "Location information is not generated to store and send."); 
      } 
     } 
    } 
} 

위치 업데이트 타이머 클래스하십시오 PendingIntent와

/** 
* LocationUpdateTimer Constructor 
*/ 
public LocationUpdateTimer(Context context, String userActivity, 
     boolean isTosend) { 
    // Save the context 
    mContext = context; 
    mUserCurrentActivity = userActivity; 
    isToSendLocationInfo = isTosend; 
} 

/** 
* To start the location reporting 
*/ 
private void startLocationReporting() { 
    if (mLocationProviderStatusListener != null) { 
     mLocationProviderStatusListener 
       .requestLocationProvidersToUpdateStatus(mConstants.EMPTY_STRING); 
     scheduleTimerTask(); 
    } 
} 

/** 
* To schedule the 20 seconds timer task to get the best location 
* information and send it to Fleetilla server. 
*/ 
private void scheduleTimerTask() { 
    bestGPSInfoTimerHandler = new Handler(); 
    bestGPSInfoTimerHandler.postDelayed(bestGPSInfoRunnable, 
      Constants.TIMER_TASK_DELAY); 
    mAppUtilInstance.logDebugMessage(TAG, 
      "20 Sec Location Update TimerTask Scheduled"); 
} 

/** 
* To cancel the timer tack which was scheduled for 30sec location update 
*/ 
private void cancelTimerTask() { 
    if (bestGPSInfoTimerHandler != null) { 
     mAppUtilInstance.logDebugMessage(TAG, "20 sec TimerTask canceled"); 
     bestGPSInfoTimerHandler.removeCallbacks(bestGPSInfoRunnable); 
     bestGPSInfoTimerHandler = null; 
    } 
} 
/** 
* A runnable will be called after the 20 sec time interval 
*/ 
Runnable bestGPSInfoRunnable = new Runnable() { 
    @Override 
    public void run() { 
     // Called after 20 seconds 
     mAppUtilInstance.logDebugMessage(TAG, 
       "TimerTask running after 20 sec interval."); 
     stopLocationReporting(); 
     cancelTimerTask(); 

     if (isToSendLocationInfo) { 
      // Check whether the location information is returned by the 
      // google api 
      if (mSharedPrefManager.checkForLocationEntityPref() 
        && mSharedPrefManager.getLocationEntityPref() 
          .getLatitude().length() > 0) { 
       // Send the packet information to the server 
       StoreAndSendLocationInformation storeAndSendLocationInformation = new StoreAndSendLocationInformation(
         mContext, 
         mSharedPrefManager.getLocationEntityPref(), 
         mUserCurrentActivity); 
       storeAndSendLocationInformation.storeAndSend(); 
      } else { 
       // If the location information is not available 
       mAppUtilInstance 
         .logDebugMessage(TAG, 
           "Location information is not generated to store and send."); 
       mAppUtilInstance 
         .broadcastStatusMessage(
           mContext, 
           Constants.STATUS_MSG_127 
             + "Location information is not generated to store and send.", 
           Constants.STATUS_CODE_127); 
      } 
     } 

    } 
}; 
+0

'onReceive' 메소드에 대한 코드를 보여줄 수 있습니까? –

+0

'PendingIntent.getBroadcast' 메소드에서 다른 'requestCode'를 사용하여 여러 개의 알람을 시작할 수 있습니까? –

+1

이미 다른 요청 코드로 2 개의 다른 알람을 구현했습니다. 나는이 게시물과 함께 내 onreceive 코드를 업데이 트됩니다. –

답변

1

안드로이드 API (11) 때문에 당신은 onReceive() 방법에 goAsync()를 호출 할 수 있습니다. 이 메서드는 PendingResult 유형의 개체를 반환합니다. 안드로이드 시스템은이 객체에 PendingResult.finish()을 호출 할 때까지 수신자를 살아 있다고 간주합니다. 이 옵션을 사용하면 수신자에서 비동기 처리를 트리거 할 수 있습니다. 해당 스레드가 완료 되 자마자 작업은 finish()을 호출하여 Android 시스템에이 구성 요소를 재활용 할 수 있음을 나타냅니다.

Sample ProjectgoAsync()BroadcastReceiver에 표시합니다.

+0

나는 시도했다. 나는 20 초의 지연된 지체와 함께 Handler를 시작했다. 그러나 앱이 종료되면 지정된 시간 간격으로 처리기를 호출하지 않습니다. 나는 goAsync()도 시도했다. 하지만 수신기는 여전히 살아 있다고 생각하지 않습니다. –

+0

위의'goAsync' 예제 코드를 참고하십시오. –

0

알람 관리기 작동합니다. 이것은 내가 내 애플 리케이션 중 하나에 그것을 할 방법은 다음과 같습니다

myAlarm = (AlarmManager) getSystemService(ALARM_SERVICE); 
    Intent myNewIntent = new Intent(MyCurrentActivityClass.this, MyNewActivityClass.class); 
    Calendar wakeUpTime = Calendar.getInstance(); 
    wakeUpTime.add(Calendar.MILLISECOND, (int) myTimeRemaining); 

    myPendingIntent = PendingIntent.getActivity(MyCurrentActivityClass.this, 0, myNewIntent, 0); 
    myAlarm.set(AlarmManager.RTC_WAKEUP, wakeUpTime.getTimeInMillis(), myPendingIntent); 

는 또한 장치를 깨워 당신의 MyNewActivityClass에 다음을 넣어 보안 화면을 통해 표시 할 수 있습니다.

public void onAttachedToWindow() { 
    //make the activity show even the screen is locked. 
    Window window = getWindow(); 

    window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON 
      + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 
      + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON 
      + WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); 
} 
+0

이 대답은 왜 -1입니까? 이 질문에 설명 된 내용을 정확히 수행하는 것은 앱의 코드입니다. – TTransmit

+0

알람 수신 중입니다. 이 메토 안에서 타이머를 구현해야합니다. 공유 한 코드는 알람을 설정하는 것입니다. 벌써 했어. –

+1

내 대답에 -1이 주어 졌을 때 클래스 또는 Java의 내용을 게시하지 않았으므로 내 대답이 문제의 유효한 해결 방법입니다. 비록 그것이 정확히 어떻게 작동하는지는 기능적으로 당신이 원하는 것을 할 것입니다. 내 앱을 테스트했는데 앱을 종료해도 활동이 시작됩니다. – TTransmit