我有一个服务(在清单文件中正确声明)是在的onDestroy()安排其自身又通过 AlarmManager 。然而,服务没有启动,即使的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();}在清单文件中的服务声明:
<服务 机器人:名字=com.xxxx.MyService 机器人:出口=真正的>< /服务>解决方案
首先,你的广播接收器是的onDestroy结束后要离开纳秒( ),使其失去作用。请在清单与注册广播接收器 A <接收方式> 元素
二, _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的服务没有启动
发布评论