我有一个活动和一个后台服务。我通过 Activity 中的 Intent 启动服务。即使 Activity 关闭,Service 也会无限期运行。但是这里的问题是,如果我从任务管理器中清除内存,服务就会停止并且不会再次启动,直到 Activity 再次启动。我希望服务在内存被清除一段时间后自动启动。我怎么能做到这一点?请帮忙。
问问题
1087 次
2 回答
0
AlarmManager service = (AlarmManager) getApplicationContext().getSystemService(
Context.ALARM_SERVICE);
Intent i = new Intent(this, BackgroundService.class);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
PendingIntent pending = PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),30000, pending);
此代码为 true 30000 毫秒运行 backgroundService
于 2013-08-18T09:35:38.177 回答
0
使用AlarmManager安排运行您的服务。
在您的主要(根)活动中:
@Override
public void onStop() {
super.onStop();
AlarmManager service = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
Intent i = new Intent(this, MyService.class);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
PendingIntent pending = PendingIntent.getService(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
service.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
REPEAT_TIME, pending);
}
这将在您的活动停止后 30 秒内启动服务。或者,您可以定义 BroadcastReceiver 它将检查服务是否正在运行并启动它。为此,只需创建广播PendingIntent
。
您可以在Android 服务教程中找到更多代码和示例。
于 2012-10-06T14:06:46.443 回答