Android 通过广播启动另一个应用的Activity

需求:现在有应用A和应用B,我需要在A应用中启动B应用中的某个Activity

实现:A应用中的Activity发送广播,关键代码如下:

       String broadcastIntent = "com.example.android.notepad.NotesList";//自己自定义
       Intent intent = new Intent(broadcastIntent);
       this.sendBroadcast(intent);

B应用中需要一个BroadcastReceiver来接收广播,取名TestReceiver继承BroadcastReceiver重写onReceive方法启动一个activity,关键代码如下:   

if(intent.getAction().equals("com.example.android.notepad.NotesList")){
        Intent noteList = new Intent(context,NotesList.class);
        noteList.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(noteList);
}

到这代码就完成了,当然在AndroidManifest.xml中要对TestReceiver进行注册,代码如下:

     <receiver android:name="TestReceiver">
             <intent-filter>
                  <action android:name="com.example.android.notepad.NotesList"/>
            </intent-filter>
    </receiver>

这样就完成了通过广播启动另一个应用Activity。

注意问题:Context中有一 个startActivity方法,Activity继承自Context,重载了startActivity方法。如果使用 Activity的startActivity方法,不会有任何限制,而如果使用Context的startActivity方法的话,就需要开启一个新 的task,解决办法是,加一个flag,也就是这句 noteList.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);的作用。如果不添加这句,就会报 android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity,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?

posted @ 2015-01-30 12:24  星辰之力  阅读(7504)  评论(0编辑  收藏  举报