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

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

2016-07-26 16:42 344 查看
原文:http://www.cnblogs.com/keshuangjie/archive/2012/08/31/2665298.html

需求:现在有应用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?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android