即使应用程序在后台,我也会尝试安排闹钟运行。如果应用程序位于前台,则下面的代码运行正常。但是,只要我按下后退按钮,我就会得到一个"泄漏的Intent Receiver错误"暗示我错过了对unregisterReceiver()的调用。我尝试将unregisterReceiver(receiver)
添加到onStop()
和onPause()
,但仍然会遇到相同的错误。非常感谢任何帮助!
另外一个附带问题,如果我最终弄清楚如何取消注册接收器,那么会阻止我的警报触发吗?感谢。
// Alarm
public void SetAlarm()
{
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive( Context context, Intent _ )
{
// code to run when alarm hits
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*10, pintent );
}