从Service启动Activity

    xiaoxiao2021-03-26  27

    Intent intent = new Intent(MyService.this, MainActivity.class); startActivity(intent);

    该方法会报错

    E/AndroidRuntime: FATAL EXCEPTION: Timer-0 Process: com.study.study, PID: 32733 android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

    好吧,按照AS的友情提示,添加上intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    Intent intent = new Intent(MyService.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);

    虽说这样解决了启动Activity的问题,但是这样有一个弊端,会产生新的Task,相当于又启动了一个任务,这也就导致程序的内存增大。

    转载请注明原文地址: https://ju.6miu.com/read-662538.html

    最新回复(0)