zoukankan      html  css  js  c++  java
  • 在广播中启动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?

  • 相关阅读:
    PHP全路径无限分类原理
    SecureCRT上传bash: rz: command not found
    Android利用Fiddler进行网络数据抓包【怎么跟踪微信请求】
    Creating the Help Page in ASP.NET Web API
    Windows上怎么安装ELK
    安装ELK
    How to kill a process on a port on linux 怎么杀死 关掉一个端口
    How to install Mysql in the CentOS
    Hadoop: Setup Maven project for MapReduce in 5mn
    Install Ambari 2.2.0 from Public Repositories(Hadoop)
  • 原文地址:https://www.cnblogs.com/vegetate/p/9997347.html
Copyright © 2011-2022 走看看