我有一个活动和后台服务。我通过活动的Intent启动服务。即使活动已关闭,服务也会无限期地运行。但是这里的问题是,如果我从任务管理器中清除内存,则服务停止并且不会再次启动,直到再次启动活动。我希望服务在内存清空一段时间后自动启动。我怎么能做到这一点?请帮忙。从活动调用后台服务
0
A
回答
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 Service Tutorial。
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);
这个代码是真正的30000毫秒运行backgroundService
相关问题
- 1. 从后台服务启动Android活动
- 2. Android:活动不会从后台执行onNewIntent()(从服务调用)
- 3. Android:从后台服务开始活动
- 4. 从后台线程中调用活动
- 5. 从BroadcastReceiver调用后台服务
- 6. 从后台线程调用WCF服务
- 7. 如何在后台启动服务并从该服务启动一项活动?
- 8. 更新前台服务notificaton从活动
- 9. 从服务中调用活动
- 10. 如何从活动调用服务?
- 11. 从服务调用的活动
- 12. 后台任务和活动
- 13. 将数据从后台服务发送到当前在后台的活动
- 14. 反应本机 - 从后台服务开始活动
- 15. 如何从后台服务开始活动
- 16. 在后台服务启动线程时调用或发送消息给活动
- 17. 从WCF工作流服务代码活动调用wcf服务
- 18. 活动从服务
- 19. android服务回调从asynctask到活动
- 20. 如果pendingintent调用getService()多次启动生活后台服务会怎么样
- 21. 活动崩溃后的Android停止后台服务
- 22. 我应该使用服务而不是后台活动吗?
- 23. 使用Subversion并推送到舞台然后活动服务器
- 24. 跨移动后台服务
- 25. 后台任务中的活动或服务?
- 26. 从后台更新前台活动
- 27. AlarmManager不调用后台服务
- 28. 如何在后台调用Web服务?
- 29. Android后台线程:从活动启动和服务启动之间的区别
- 30. 保持活力在后台服务?
我跟着你提到的教程。但是,RAM存储器被清除时,服务不会自动启动。 – mithu
您的示例启动服务并使其即使在活动关闭后仍保持运行。但是在RAM内存被清除之后,Service始终不会自动启动,直到Activity启动。我有一个想法,请告诉我,如果这可以遵循。服务应作为可通过BroadcastReceiver启动的不同应用程序编写。服务和活动共享本地数据库。所以应该创建一个ContentProvider来在这两个应用程序之间共享数据库。这可能吗? – mithu
即使应用程序停止,我的示例服务也会启动。 – marwinXXII