I basically do all the work inside onCreate()
and use onStartCommand()
only to get a string from the intent and stop the service.
This is MyService.java code:
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
if(intent != null)
this.test = intent.getStringExtra("test");
String action = intent.getAction();
if (action != null) {
if (action.equals("Stop")) {
stopForeground(true);
stopSelf();
return START_NOT_STICKY;
}
}
//return START_STICKY;
return START_REDELIVER_INTENT;
}
My MainActivity simply start the service like this:
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("test", test);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startForegroundService(intent);
else
startService(intent);
and stop the service like this:
Intent stopServiceIntent = new Intent(MainActivity.this,MyService.class);
stopServiceIntent.setAction("Stop");
startService(stopServiceIntent);
In another question I asked yesterday, someone suggested that I should stop the service directly by using stopService(intent)
so that I wouldn't need to start the service again and pass a string in order to stop it. I suppose by doing so I would to move the call stopForeground(true)
from onStartCommand()
in onDestroy()
.
I would like to ask you if this approach is equivalent of mine.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…