Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...