定于AlarmManager Android的服务没有启动 [英] Android service scheduled on AlarmManager not starting
问题描述
我有一个服务(在清单文件中正确声明)是在的onDestroy()
安排其自身又通过 AlarmManager <一分钟后开始/ code>。然而,服务没有启动,即使
的onDestroy()
运行正常。可能是什么问题?
调度code:
@覆盖
公共无效的onDestroy(){ 广播接收器BR =新的广播接收器(){
@覆盖
公共无效的onReceive(上下文C,意图我){
c.startService(新意图(C,MyService.class));
}
}; registerReceiver(BR,新的IntentFilter(XXXX)); PI的PendingIntent = PendingIntent.getBroadcast(这一点,0,新的意向(XXXX),0); AlarmManager点=(AlarmManager)(this.getSystemService(Context.ALARM_SERVICE)); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+ ONE_MINUTE,PI); Log.i(的onDestroy,服务调度。); unregisterReceiver(BR); super.onDestroy();
}
在清单文件中的服务声明:
&LT;服务
机器人:名字=com.xxxx.MyService
机器人:出口=真正的&GT;
&LT; /服务&GT;
首先,你的广播接收器
是的onDestroy结束后要离开纳秒( )
,使其失去作用。请在清单与注册广播接收器
A &lt;接收方式&gt;
元素
二, _WAKEUP
报警只能保持设备清醒足够长的时间在处理一个的onReceive()
广播接收器
。你需要使用激活锁定
来保持设备比清醒更长时间。这取决于你在做什么,我的 WakefulIntentService
可能会有些用处。
第三,你不需要导出服务,并通过这样做,你打开了潜在的安全漏洞。我建议删除的android:出口=真正的
I have a service (properly declared in the Manifest file) that upon onDestroy()
schedules itself to start again one minute later via AlarmManager
. However the service is not starting even though onDestroy()
runs correctly. What could be wrong?
The scheduling code:
@Override
public void onDestroy() {
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
c.startService(new Intent(c, MyService.class));
}
};
registerReceiver(br, new IntentFilter("xxxx"));
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent("xxxx"), 0);
AlarmManager am = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ONE_MINUTE, pi);
Log.i("onDestroy", "Service scheduled.");
unregisterReceiver(br);
super.onDestroy();
}
The service declaration in the Manifest file:
<service
android:name="com.xxxx.MyService"
android:exported="true">
</service>
First, your BroadcastReceiver
is going away nanoseconds after the end of onDestroy()
, making it useless. Please register your BroadcastReceiver
in the manifest with a <receiver>
element.
Second, a _WAKEUP
alarm only keeps the device awake long enough to process an onReceive()
in a BroadcastReceiver
. You need to use a WakeLock
to keep the device awake longer than that. Depending upon what you are doing, my WakefulIntentService
may be of some use.
Third, you do not need to export your service, and by doing so, you are opening up potential security holes. I recommend removing android:exported="true"
.
这篇关于定于AlarmManager Android的服务没有启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!