Android 完成后未触发警报

Android Alarm not triggered after finishing

当我完成 activity 之前我的闹钟没有触发。 当我只呆在 activity 时,闹钟工作正常。 这是代码:

 AlarmManager alarms = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    final BroadcastReceiver receiver_daily = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "DAILY BONUS");
            String title = getResources().getString(R.string.playreminder_daily_title);
            String text = String.format(getResources().getString(R.string.playreminder_daily_text), getResources().getInteger(R.integer.daily_bonus_coins));
            showDailyBonusNotification(title, text);
            unregisterReceiver(this);
            Account.setBonusAvailable(true, getApplicationContext());
        }

    };
    registerReceiver(receiver_daily, new IntentFilter("com.doopy.numbers.ACTION_PLAYREMINDER_DAILY"));

    PendingIntent operation = PendingIntent.getBroadcast(getApplicationContext(), RQC_BROADCAST, new Intent("com.doopy.numbers.ACTION_PLAYREMINDER_DAILY"), 0);
    alarms.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+DAILY_BONUS_TIME, operation);
    addCoinsAnimated(Account.getCoins(getApplicationContext()), getResources().getInteger(R.integer.daily_bonus_coins), 500, true, getApplicationContext());
    Account.setBonusAvailable(false, getApplicationContext());
    mGetBonusLayout.setVisibility(View.GONE);

我还注意到我收到了这个泄漏警告:

android.app.IntentReceiverLeaked: Activity com.doopy.numbers.GameOverActivity has leaked IntentReceiver com.doopy.numbers.GameOverActivity@41c33780 that was originally registered here. Are you missing a call to unregisterReceiver()?

我不想在 activity finished/is 销毁后取消注册我的闹钟,因为它应该会触发一个通知,表明现在可以使用每日奖金,尽管应用程序可能不可用运行.

关于泄漏警告,您可以像这样在您的清单中定义您的接收器

<receiver android:enabled=["true" | "false"]
          android:exported=["true" | "false"]
          android:icon="drawable resource"
          android:label="string resource"
          android:name="string"
          android:permission="string"
          android:process="string" >
    . . .
</receiver>

这将为您提供预期的行为。 Reference here.

一个例子:

<receiver android:name="MyReceiver" >
    <intent-filter>
        <action android:name="com.doopy.numbers.ACTION_PLAYREMINDER_DAILY" />
    </intent-filter>
</receiver>