我有两个应用程序A1和B1.A1有一个广播接收器,我想从B1注册这个广播接收器。所以我试过
Intent intent = new Intent();
intent.setClassName("pkgname","pkgname.BroadCastReceiverName");
intent.setAction("xxx.x...xxx");
getApplicationContext().sendBroadcast(intent);
但它不会触发/注册任何接收器。
如何在另一个应用程序中访问一个应用程序的广播接收器?
先谢谢
答案 0 :(得分:0)
应用程序-B1中的broadcastReceiver应该在AndroidManifest.xml文件中注册,并使用从application-A1广播的相应intent-filter。
答案 1 :(得分:0)
首先,在使用这样的反射时总是会进行一些错误检查,因为用户手机上可能无法使用所需的包和接收器。 上面的方法应该可以工作,但你必须先设置一些先决条件: 将android:exported =“true”设置为另一个应用程序中的广播接收器 安装后至少运行一次其他应用程序,因为只有当用户在列表中运行一次应用程序时才会注册此类全局接收器。我认为这是从android 4.x开始的情况,但在旧版本上可能是相同的(如果有人知道更改时的确切版本请添加)
答案 2 :(得分:0)
你可以在App A1的Activity中创建一个方法(例如register())(例如Activity1)并添加一些代码来注册它的brodcastreceiver。在Activity1的onCreate()中检查它的{{1如果它在Activity1的onCreate()中有一个键,例如Intent
调用register()。现在,当您想要注册广播记录器时,只需从App B1启动Activity1,其意图是具有该特定密钥的额外功能,例如reg
。
答案 3 :(得分:0)
Hope this will work for you,
In App1: calling a Broadcast Receiver(Name of my broadcast receiver "MyBroadCastReceiver") of App2.
you can place this method in any Button onClick() or as per your requirement.
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);
}
In App2: Called broadcast receiver which is Located in 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();
}
}
}
}
In App2: AndroidManifest.xml file add this below code inside your application tag
<receiver
android:name=".MyBroadCastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="youActionName" />
</intent-filter>
</receiver>