Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

java - stopService(intent) equivalent of startService(intent) and then stopping it inside onStartCommand()?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...