2016-08-14 49 views
1

this article,如果我需要實現自動從我的數據庫中刪除某些行(比目前的時間早),只有當某些活動是開放的,我必須使用ResultReceiver:如何一起使用Resultreceiver和AlarmManager?

ResultReceiver - 用於發送通用回調接口服務和活動之間的結果。如果您的服務只需要在一個地方連接其父應用程序,請使用此方法。

和AlarmManager:

觸發在未來或重複間隔

指定的時間,但我面對的,我不知道如何使用AlarmManager與ResultReceiver問題。我的意思是我不明白如何從Activity調用我的IntentService。

在我的意圖的服務,我有類似的東西:

@Override 
    protected void onHandleIntent(Intent intent) { 
     Log.d(LOG_TAG, "Inside onHandleIntent"); 
     ResultReceiver rec = intent.getParcelableExtra(IntentConstants.UPDATE_REMINDERS_SERVICE_RECEIVER); 
     int rowsDeleted = notificationService.deleteAllOld(Calendar.getInstance().getTimeInMillis()); 

     Bundle bundle = new Bundle(); 
     bundle.putString(IntentConstants.UPDATE_REMINDERS_SERVICE_NOTIFICATIONS_DELETED, "Rows deleted: " + rowsDeleted); 
     // Here we call send passing a resultCode and the bundle of extras 
     rec.send(Activity.RESULT_OK, bundle); 

    } 

而且在活動時間:

// Starts the IntentService 
    public void onStartService() { 
     Log.d("UpdateRemindersLog", "Inside onStartService"); 
     final Intent i = new Intent(this, UpdateRemindersService.class); 
     i.putExtra(IntentConstants.UPDATE_REMINDERS_SERVICE_RECEIVER, remindersReceiver); 
     startService(i); 
    } 

我試圖實現onStartService方法內AlarmManager,但它不工作。我認爲它會是這樣的:

Intent intent = new Intent(getApplicationContext(), UpdateRemindersReceiver.class); 
intent.putExtra(IntentConstants.UPDATE_REMINDERS_SERVICE_RECEIVER, remindersReceiver); 
// Create a PendingIntent to be triggered when the alarm goes off 
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, UpdateRemindersService.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

long firstMillis = System.currentTimeMillis(); // alarm is set right away 
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 10*1000, pendingIntent); 

那麼,有人可以解釋我如何可以實現與IntentService AlarmManager? 謝謝。

回答

0

如方法所示,PendingIntent.getBroadcast()呼叫的目標需要是廣播接收器。 AlarmManager只適用於Intent

所以你需要添加處理AlarmManager的信號的廣播接收器,然後開始你的服務:

public class AlarmReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Start your service here 
    } 
} 

還有,記得註冊您的接收器在AndroidManifest.xml文件像這樣(裏面你application標籤):

<receiver 
    android:name=".AlarmReceiver" 
    android:enabled="true" /> 

當您創建Intent你現在應該針對新的接收機類(AlarmReceiver.class)。

+0

我剛剛發現IntentService和AlarmManager都是「啓動器」。所以我的代碼很愚蠢。但是這個人有任何幫助! –