[英]Android service gets restarted when application is removed from Recent Apps list
Code to start the service on button click 单击按钮即可启动服务的代码
public void serviceBtnClicked(View view) {
SharedPreferences sharedPreferences = getSharedPreferences("my.package.name", MODE_PRIVATE);
if (!sharedPreferences.getBoolean("_done", false) && !isMyServiceRunning(MyService.class)) {
startService(new Intent(this, MyService.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
MyService.java MyService.java
@Override
public void onCreate() {
Log.d("_pop", "create");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new MyFirstTask().execute();
return super.onStartCommand(intent, flags, startId);
}
public class MyFirstTask extends AsyncTask<String, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(String... params) {
doStuff(0);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
SharedPreferences sharedPreferences = getSharedPreferences("my.package.name", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("_done", true);
editor.apply();
super.onPostExecute(aVoid);
}
}
When I click the button, the service starts as expected and does all the work properly. 当我单击按钮时,该服务将按预期方式启动,并且可以正常进行所有工作。 But the problem is when I remove my application from the Recent Apps list the service get started again .
但是问题是, 当我从“最近使用的应用程序”列表中删除我的应用程序时,该服务又重新启动了 。 One interesting thing is that when I restart the application, the service does not starts which means that the SharedPreferences
_done
boolean check is working. 一件有趣的事是,当我重新启动应用程序时,该服务未启动,这意味着SharedPreferences
_done
布尔检查正在运行。
Ideally, you would replace your entire service with an IntentService
, getting rid of your AsyncTask
(not used by services) and putting your doInBackground()
and onPostExecute()
code into onHandleIntent()
. 理想情况下,您可以将整个服务替换为
IntentService
,摆脱AsyncTask
(服务不使用),并将doInBackground()
和onPostExecute()
代码放入onHandleIntent()
。
Beyond that, replace: 除此之外,请替换:
return super.onStartCommand(intent, flags, startId);
with: 有:
return START_NOT_STICKY;
as the default of onStartCommand()
is to start a sticky service, meaning that the service will be restarted automatically some time after your process is terminated. 因为
onStartCommand()
的默认设置是启动粘性服务,这意味着该服务将在您的进程终止后的某个时间自动重新启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.