android start activity from service

后端 未结 7 1207
傲寒
傲寒 2020-11-22 03:04

Android:

public class LocationService extends Service {

@Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startI         


        
7条回答
  •  醉梦人生
    2020-11-22 03:47

    Another thing worth mentioning: while the answer above works just fine when our task is in the background, the only way I could make it work if our task (made of service + some activities) was in the foreground (i.e. one of our activities visible to user) was like this:

        Intent intent = new Intent(storedActivity, MyActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        storedActivity.startActivity(intent);
    

    I do not know whether ACTION_VIEW or FLAG_ACTIVITY_NEW_TASK are of any actual use here. The key to succeeding was

    storedActivity.startActivity(intent);
    

    and of course FLAG_ACTIVITY_REORDER_TO_FRONT for not instantiating the activity again. Best of luck!

提交回复
热议问题