Resultreceiver 和AlarmManager 如何一起使用?

How to use Resultreceiver and AlarmManager together?

根据 this article,如果我需要实现仅当某些 activity 打开时从我的数据库中自动删除某些行(早于当前时间),我必须使用 ResultReceiver:

ResultReceiver - Generic callback interface for sending results between service and activity. If your service only needs to connect with its parent application in a single place, use this approach.

和报警管理器:

Trigger at a specified time in the future or at a recurring interval

但是我遇到了一个问题,我不知道如何将 AlarmManager 与 ResultReceiver 一起使用。我的意思是我不明白如何从 Activity.

调用我的 IntentService

在我的 Intent 服务中,我有类似的东西:

@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);

    }

在Activity中:

// 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 吗? 谢谢。

PendingIntent.getBroadcast() 调用的目标需要是一个广播接收器,正如方法所建议的那样。 AlarmManager 仅适用于那些 Intents。

因此您需要添加一个广播接收器来处理 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 时,您现在应该将新接收器设为目标 class (AlarmReceiver.class)。