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,相当于又启动了一个任务,这也就导致程序的内存增大。
本文探讨了从Android Service中启动Activity的方法,并介绍了如何正确使用FLAG_ACTIVITY_NEW_TASK标志来避免错误。同时,文中还讨论了这种方法可能导致的新Task创建问题及对程序内存的影响。
350

被折叠的 条评论
为什么被折叠?



