在 Service 中启动 Activity,有很多方式,比如隐式启动、显式启动等。
隐式启动 Activity,需要在manifest.xml 中为该 Activity 配置 <intent-filter>,如下所示:
<activity android:name=".MyActivity" > <intent-filter> <action android:name="mark.zhang"></action> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity>
在 Service 中这样启动 MyActivity:
// 等效于 // Intent i = new Intent(); // i.setAction("mark.zhang"); Intent i = new Intent("mark.zhang"); // 这个不是必需的 i.addCategory(Intent.CATEGORY_DEFAULT); startActivity(i);
Intent i = new Intent(this, DialogActivity.class); startActivity(i);
10-06 19:30:50.895: ERROR/AndroidRuntime(5789):
Caused by: android.util.AndroidRuntimeException:
Calling startActivity() from outside of an Activity
context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? 10-06 19:30:50.895: ERROR/AndroidRuntime(5789): at android.app.ApplicationContext.startActivity(ApplicationContext.java:550) 10-06 19:30:50.895: ERROR/AndroidRuntime(5789): at android.content.ContextWrapper.startActivity(ContextWrapper.java:248) 10-06 19:30:50.895: ERROR/AndroidRuntime(5789): at com.wpstar.receiver.ServerService.onStartCommand(ServerService.java:34) 10-06 19:30:50.895: ERROR/AndroidRuntime(5789): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2873) 10-06 19:30:50.895: ERROR/AndroidRuntime(5789): ... 10 more
10-06 19:30:50.895: ERROR/AndroidRuntime(5789):
Caused by: android.util.AndroidRuntimeException:
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.
Is this really what you want?
// 等效于 // Intent i = new Intent(); // i.setAction("mark.zhang"); Intent i = new Intent("mark.zhang"); // 这个不是必需的 i.addCategory(Intent.CATEGORY_DEFAULT); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i);
Intent i = new Intent(this, MyActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i);
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);