简体   繁体   English

如何将广播从一个应用程序发送到另一个应用程序

[英]How to Send BroadCast from one app to another app

I have App A and App B. In App AI want to send broadcast to App B. This is the code for App A:我有 App A 和 App B。在 App AI 中,要向 App B 发送广播。这是 App A 的代码:

final Intent intent = new Intent();
intent.setAction("com.pkg.perform.Ruby");
intent.putExtra("KeyName", "code1id");
intent.setComponent(new ComponentName("com.pkg.AppB", "com.pkg.AppB.MainActivity"));
sendBroadcast(intent);

And in App B - In MainActivity , I have MyBroadCastReceiver Class.在 App B - 在MainActivity ,我有MyBroadCastReceiver类。

public class MainActivity extends Activity {
    private MyBroadcastReceiver MyReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Receive broadcast from External App
        IntentFilter intentFilter = new IntentFilter("com.pkg.perform.Ruby");
        MyReceiver = new MyBroadcastReceiver();
        if(intentFilter != null)
        {
            registerReceiver(MyReceiver, intentFilter);
        }
    }

    public class MyBroadcastReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(MainActivity.this, "Data Received from External App", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(MyReceiver != null)
            unregisterReceiver(MyReceiver);
    }
}

I am getting the error - Receiver is not registered .我收到错误 -接收器未注册

First thing first declare the receiver in app B in the manifest file like this:首先,首先在清单文件中的 app B 中声明接收器,如下所示:

<receiver android:name=".MyBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
        <intent-filter>
          <action android:name="com.pkg.perform.Ruby" />
        </intent-filter>
</receiver>

when sending the broadcast add FLAG_INCLUDE_STOPPED_PACKAGES flag to the intent [src] because when you broadcast from app A to app B , app B might not be running, this flag insures that the broadcast reachs out even apps not running:发送广播时,将FLAG_INCLUDE_STOPPED_PACKAGES标志添加到意图[src] 中,因为当您从应用程序 A 广播到应用程序 B 时,应用程序 B 可能未运行,此标志可确保即使应用程序未运行,广播也能到达:

FLAG_INCLUDE_STOPPED_PACKAGES flag is added to the intent before it is sent to indicate that the intent is to be allowed to start a component of a stopped application. FLAG_INCLUDE_STOPPED_PACKAGES 标志在发送之前添加到意图中,以指示允许意图启动已停止应用程序的组件。

intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);

In your case it will be like this:在你的情况下,它会是这样的:

    final Intent intent=new Intent();
    intent.setAction("com.pkg.perform.Ruby");
    intent.putExtra("KeyName","code1id");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    intent.setComponent(  
        new ComponentName("com.pkg.AppB","com.pkg.AppB.MyBroadcastReceiver"));  
    sendBroadcast(intent);

In App A: Send the broadcast here.在 App A 中:在此处发送广播。

 final Intent i= new Intent();
 i.putExtra("data", "Some data");
 i.setAction("com.pkg.perform.Ruby");
 i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
 getApplicationContext().sendBroadcast(i);

In App B manifest在 App B 清单中

 <receiver  android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.pkg.perform.Ruby" />
            </intent-filter>
        </receiver>

In App B MainActivity: register the receiver oncreate(), and unregister onDestroy()在 App B MainActivity 中:注册接收者 oncreate(),并取消注册 onDestroy()

 public class MainActivity extends AppCompatActivity
 {
      private MyBroadcastReceiver MyReceiver;

       @Override
       protected void onCreate(Bundle savedInstanceState)
       {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            MyReceiver = new MyBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter("com.pkg.perform.Ruby");
            if(intentFilter != null)
            {
               registerReceiver(MyReceiver, intentFilter);
            }
       }

       @Override
       protected void onDestroy()
       {
           super.onDestroy();
           if(MyReceiver != null)
               unregisterReceiver(MyReceiver);
       }
  }

In App B BroadcastReceiver在 App B 中广播接收器

public class MyBroadcastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String data = intent.getStringExtra("data");
        Log.i("BR" ,"Data received:  " + data);
    }
}

There may be two cases :可能有两种情况:

  1. Your appB is not running, hence the activity is not instantiated, and so the receiver is not registered.您的 appB 未运行,因此未实例化活动,因此未注册接收器。
  2. Your activity is destroyed, means that you have unregistered your receiver that you registered via registerReceiver() in onCreate()您的活动已被销毁,这意味着您已取消注册您在 onCreate() 中通过 registerReceiver() 注册的接收器

Solution :解决方案 :

Register your broadcast receiver in manifest.在清单中注册您的广播接收器。

Inside manifest of appB : appB 的内部清单:

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="com.pkg.perform.Ruby" />
    </intent-filter>
</receiver>

And comment out the line in appA并注释掉 appA 中的行

intent.setComponent(new ComponentName("com.pkg.AppB","com.pkg.AppB.MainActivity"));

Write the logic in MyBroadcastReceiver to display relevant data/launch new activity在 MyBroadcastReceiver 中编写逻辑以显示相关数据/启动新活动

MyReceiver is class not object. MyReceiver 是类而不是对象。 Create创建

myReceiver = new MyReceiver(); 

and put...........并把......

registerReceiver(myReceiver,intentFilter);

If this helps some one and it works for me如果这对某人有帮助并且对我有用

In App A in activity or in a content provider-在应用程序 A 中的活动或内容提供者中-

  Intent intent = new Intent("Updated");
  intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
  intent.setComponent (new
  ComponentName "com.exam.appA",
  "com.exam.appA.DbaseChanged"));
  getContext().sendBroadcast(intent);

In App B in the manifest在清单中的 App B 中

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

In App B Broadcast receiver class-在 App B 广播接收器类中-

    public class DbaseChanged extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent
     intent)   {

           String act = intent.getAction();
           if(act != null && act.equals("Updated")  )
            {
                Toast.makeText(context, act ,
              Toast.LENGTH_SHORT).show();

            }

            }
       }

I needed to call setPackage("package_name") to ensure explicitness when I registered the broadcast receiver in the Manifest.当我在清单中注册广播接收器时,我需要调用setPackage("package_name")以确保明确性。 I was then able to receive the data even if the app was closed completely.即使应用程序完全关闭,我也能够接收数据。

// sending app sends broadcast
Intent intent = new Intent(ACTION_RECOMMEND);
intent.putExtra(LISTEN_RECOMMENDATION, "Triggered - Jhene Aiko");
intent.putExtra(WATCH_RECOMMENDATION, "Goblin - Kim Go-eun");
intent.setPackage("com.example.package.receiverapp");
sendBroadcast(intent);


//receiving app manifest registers receiver
<receiver
   android:name=".ManifestRegisteredBroadcastReceiver"
   android:exported="true">
   <intent-filter>
       <action android:name="com.random.action.RECOMMEND" />
   </intent-filter>
</receiver>

I didn't need to add intent.setPackage(package_name) when registering the receiver via an activity, but this also meant that I couldn't get the data if the activity was destroyed (app closed, app in background for long period)通过活动注册接收器时,我不需要添加intent.setPackage(package_name) ,但这也意味着如果活动被破坏,我将无法获取数据(应用程序关闭,应用程序在后台长时间运行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从一个Android应用发送广播到另一个 - Send broadcast from one Android app to another 如何将触摸事件从一个应用程序发送到另一个应用程序 - how to send touch event from one app to another app 从应用程序A发送广播并在应用程序B中接收它 - Send broadcast from App A and receiving it in app B 在 android 工作室中是否有可能通过使用同时打开的两个不同模拟器将广播从一个应用程序发送到另一个应用程序? - Is there in android studio any possibility to send a broadcast from one app to another by using two different emulators which are simultaneously open? 如何在android中将敏感数据从一个应用程序发送到另一个应用程序 - How to send sensitive data from one app to another in android Android-如何将捆绑软件从一个应用发送到另一个? - Android - How to Send Bundle from One App to Another? 是否可以从一个应用程序向另一个应用程序发送消息? - Is it possible to send a message from one app to another? 将数据从一个应用程序发送到另一个应用程序中的特定活动 - Send Data From One App to A Specific Activity in Another App 如何在android中将数据从1个应用程序发送到另一个应用程序 - How to send data from 1 app to another in android 如何将一个应用程序的SharedPreference发送到另一个? - How to send a SharedPreference from an App to another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM