当应用程序没有运行广播接收器不工作 [英] BroadcastReceiver not working when app is not running
本文介绍了当应用程序没有运行广播接收器不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的清单文件我已经宣布了接收器。 (如下图)
In my manifest file I have declared the receiver. (as follows)
<receiver android:name=".OnAlarmReceive" />
但是,一旦我关闭了我的申请,我不能够得到报警和通知。显然,我的广播接收器
到的onReceive
呼叫从来没有。
public class OnAlarmReceive extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent arg1)
{
//various stuff
}
}
在MainActivity里面,我的报警管理器类是作为如下:
Inside the MainActivity, my alarm manager class is as the follows.
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent("MY_ALARM_NOTIFICATION");
intent.setClass(this, OnAlarmReceive.class);
intent.putExtra("message", message);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(MainActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar timeCal = Calendar.getInstance();
timeCal.set(Calendar.HOUR_OF_DAY, hour);
timeCal.set(Calendar.MINUTE, minutes);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeCal.getTimeInMillis(), pendingIntent);
和我的表现为是如下:
<receiver android:name=".OnAlarmReceive">
<intent-filter android:priority="1">
<action android:name="MY_ALARM_NOTIFICATION"/>
</intent-filter>
</receiver>
我应该怎么才能收到通知/报警,即使我已经关闭我的应用程序做的。后台服务?
What should I do in order to receive the notifications/alarms even if I have shut off my app. Background service ?
推荐答案
您code工作正常!
所有你所要做的就是改变这一行:
All you have to do is to change this line:
alarmManager.set(AlarmManager.RTC_WAKEUP, timeCal.getTimeInMillis(),
pendingIntent);
这一行:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 5000, pendingIntent);
和在的onReceive的code将5000毫秒后运行(5秒),即使应用程序没有运行
And the code in the "onReceive" will run after 5000ms (5sec) even when app is not running
这篇关于当应用程序没有运行广播接收器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文