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

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

问题描述:

我有App A和AppB.在App A中,我想向App B发送广播. 这是App A的代码:

I have App A and App B. In App A I want to send broadcast to App B. This is the code for 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);

在App B中-在MainActivity中,我有MyBroadCastReceiver类.

And in App B - In MainActivity, I have MyBroadCastReceiver Class.

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);
    }
}

我遇到错误-接收器未注册.

第一件事首先是在清单文件中的应用B中声明接收方,如下所示:

First thing first declare the receiver in app B in the manifest file like this:

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

在向目标发送广播时添加FLAG_INCLUDE_STOPPED_PACKAGES标志 [src] ,因为当您从应用程序A广播到应用程序B时,应用程序B可能没有运行,此标志可确保即使没有运行的应用程序也可以广播该广播:

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标志已添加到意图中 发送以表明该意图将被允许启动一个 已停止的应用程序的组件.

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.

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);