我有一个使用以下代码从 Activity 调用的服务:
startService(new Intent(AMC_Activity.this,CallService.class));
服务运行良好约 20-30 分钟,但在该服务停止运行后,我知道我可以使用“前台”服务,但通过使用我应该显示通知,那么,有没有其他方法可以防止服务停止跑步?
我有一个使用以下代码从 Activity 调用的服务:
startService(new Intent(AMC_Activity.this,CallService.class));
服务运行良好约 20-30 分钟,但在该服务停止运行后,我知道我可以使用“前台”服务,但通过使用我应该显示通知,那么,有没有其他方法可以防止服务停止跑步?
我不确定,但我认为您是从 UI 线程启动服务,然后将您的服务置于应用程序后台,因此一段时间后您的活动实例丢失并且该 UI 线程当时也被杀死。
解决方案
创建一个新线程并使用该线程而不是 UI 线程启动服务,因为无论线程调用它,服务都在该线程上工作。
//This code will be in class body.
private Thread thread1 = new Thread(){
public void run(){
startService(new Intent(AMC_Activity.this,CallService.class));
}
}
//Now this code will be call when you are going to start the service, i.e. Under onCreate()
thread1.start();
它可能对你有帮助。
如果您在设备上使用 TaskManager 应用程序,您应该注意它不会杀死您的应用程序和/或服务。