为什么后台服务停止,同时运行? [英] Why does the background service stops while running?
问题描述
我在我的Android application.In后台服务,一个线程聆听音乐frequently.My服务最近的任务会覆盖的onCreate()
和 onStartCommand()
方法。当我试图打开像图库一些应用
,相机
等等,该服务将被stopped.It电话在的onCreate()
方法,而不是只的onDestroy()
或 onStartCommand()
。我尝试过这项服务覆盖onLowMemory(),但它记录通过指定内部保存nothing.The应用
安卓的installLocation =internalOnly
在manifest文件中。
注:本期注意到了福邦A54 2.3.5
为什么有时后台服务停止?是否有此问题的任何解决方案?
公共类的MyService扩展服务{ 公共则将MyService(){
} @覆盖
公众诠释onStartCommand(意向意图,诠释标志诠释startId){
尝试{
如果(意向!= NULL){
// ......
}
}赶上(Throwable的E){
}
返回START_STICKY;
} @覆盖
公共无效的onDestroy(){
super.onDestroy();
} @覆盖
公共无效的onCreate(){
super.onCreate();
// ......
} @覆盖
公众的IBinder onBind(意向意图){
返回null;
}
}
和启动这样的服务。
意向意图=新意图(getApplicationContext(),MyService.class);
。getApplicationContext()startService(意向);
Android版可以在任何时间以任何理由停止任何服务。一个典型的原因是低内存(查杀服务在其他地方给它的内存),但我已经看到了杀死他们无论每隔X小时,至少有几个设备。有没有办法,以确保您始终运行。你能做的最好的是有所有的活动尝试启动服务(在它没有运行的情况下),写你的服务,因此它可以重新加载所需要的数据,并设置自己作为START_STICKY所以如果它有足够的内存架构将重新启动您以后。
I have a background service in my android application.In which a thread listening recent tasks running frequently.My service overrides both onCreate()
and onStartCommand()
methods. When i tried to open some applications like Gallery
,Camera
etc..., the service will be stopped.It calls the onCreate()
method only and not onDestroy()
or onStartCommand()
.I tried to override onLowMemory() in this service but it logs nothing.The application saved internally by specifying
android:installLocation="internalOnly"
in the manifest file.
Note: This issue noticed on Micromax A54 2.3.5
.
Why does the background service stops sometimes? Is there any solution for this issue?
public class MyService extends Service {
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
if(intent != null){
//......
}
} catch (Throwable e) {
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onCreate() {
super.onCreate();
//......
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
And start the service like this
Intent intent = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(intent);
Android can stop any service at any time for any reason. A typical reason is low memory (killing the service to give its memory elsewhere), but I've seen at least a few devices that kill them every X hours regardless. There is no way to ensure you always run. The best you can do is have all your activities try to start your service (in case it isn't running), write your service so it can reload needed data, and set yourself as START_STICKY so if it has enough memory the framework will restart you later.
这篇关于为什么后台服务停止,同时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!