我有一个使用以下代码从 Activity 调用的服务:
startService(new Intent(AMC_Activity.this,CallService.class));
服务运行良好大约 20-30 分钟,但在该服务停止运行后,我知道我可以使用“前台”服务,但通过使用它我应该显示通知,所以,还有其他方法吗防止服务停止运行?
最佳答案
我不确定,但我认为你是从 UI 线程启动你的服务,然后你将你的服务放入应用程序后台,所以过了一段时间你的 Activity 实例会丢失,并且 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();
也许对你有帮助。
关于java - 防止停止android服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256219/