您的位置:首页 > 移动开发 > Android开发

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

2014-04-06 16:11 453 查看
需求:现在有应用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);//可使用onReceive中的参数intent
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?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: