【问题标题】:How to access broadcastreceiver of another application如何访问另一个应用程序的广播接收器
【发布时间】:2013-05-15 10:18:55
【问题描述】:

我有两个应用程序 A1 和 B1.A1 有一个广播接收器,我想从 B1 注册这个广播接收器。所以我尝试了

Intent intent = new Intent();
intent.setClassName("pkgname","pkgname.BroadCastReceiverName");
intent.setAction("xxx.x...xxx");
getApplicationContext().sendBroadcast(intent);

但它不会触发/注册任何接收器。

如何在另一个应用程序中访问一个应用程序的广播接收器?

提前致谢

【问题讨论】:

  • 在app A的manifest文件中添加reciever

标签: android broadcastreceiver


【解决方案1】:

希望这对你有用,

在 App1 中:调用 App2 的广播接收器(我的广播接收器名称“MyBroadCastReceiver”)。

您可以将此方法放置在任何 Button onClick() 中或根据您的要求。

 private void getAnotherAppMethod(){
    Intent intent = new Intent("Updated");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    // for Example, here packageName of app2 is "com.app2.example" and its class name with packageName can be like "com.app2.example.yourBroadCastRecevier"
    intent.setComponent(new ComponentName("package name of app2","package.yourbroadcastreciverName in app2"));
    getContext().sendBroadcast(intent);
}

在 App2 中:调用的广播接收器位于 App2 中

public class MyBroadCastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent != null)
        {
            String sIntentAction = intent.getAction();
            if (sIntentAction != null && sIntentAction.equals("youActionName"))
            {
                Toast.makeText(context, "Hello From App2", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(context,"Something went wrong",Toast.LENGTH_SHORT).show();
            }
        }

    }
}

在 App2 中:AndroidManifest.xml 文件 在您的 application 标签中添加以下代码

<receiver
       android:name=".MyBroadCastReceiver"
       android:enabled="true"
       android:exported="true">
       <intent-filter>
            <action android:name="youActionName" />
       </intent-filter>
</receiver>

【讨论】:

    【解决方案2】:

    应用程序 B1 中的广播接收器应使用您从应用程序 A1 广播的适当意图过滤器在 AndroidManifest.xml 文件中注册。

    【讨论】:

    • 我添加了 在应用程序 B1 的清单文件中。但是没有效果。
    • 一个原因可能是您的应用程序 B1 当时没有运行。请确保不是这种情况。
    • 有人遇到过类似的问题...不确定对您的事业有多大帮助...stackoverflow.com/questions/3935321/…
    【解决方案3】:

    首先,在使用这样的反射时,请务必进行一些错误检查,因为用户手机上可能没有所需的包和接收器。 上述方法应该有效,但您必须先设置一些先决条件才能使用: 在另一个应用程序中将 android:exported="true" 设置为您的广播接收器 安装后至少运行一次其他应用程序,因为像这样的全局接收器只有在用户在列表中运行一次时才会注册。我认为从 android 4.x 开始就是这种情况,但在旧版本上可能是相同的(如果有人知道更改时的确切版本,请添加)

    【讨论】:

      【解决方案4】:

      您可以在 App A1(例如 Activity1)的 Activity 中创建一个方法(例如 register()),并向其中添加一些代码来注册它的 brodcastreceiver。在 Activity1 的 onCreate() 中检查它的 Intent如果它有一个键,例如 reg 在 Activity1 的 onCreate() 中调用 register()。现在,当你想注册你的广播接收器时,从 App B1 启动 Activity1 就足够了,其 Intent 具有该特定键的额外内容,例如reg

      【讨论】:

      • 我想在应用B1中访问应用A1的广播接收器
      • @DevuSoman 请再次查看我的回答。我为您添加了更多详细信息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多