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
@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.
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()
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.