1

有人知道如何将 sendBroadcast 和 BroadcastReceiver 用于不同的应用程序吗?实际上我已经在同一个项目中使用过 sendBroadcast 和 BroadcastReceiver。现在我想尝试发送到另一个应用程序。有人知道吗?

在我之前的项目中,我在 mainActivity 中这样广播:

Intent broadCastIntent = new Intent("SendMessage");
broadCastIntent.putExtra("NAME", gameName);
broadCastIntent.putExtra("JOB",jobStatus);
broadCastIntent.putExtra("STATUS",gameStatus);
sendBroadcast( broadCastIntent );
Log.d("Broadcast sent", gameName );

我还添加了检查意图的方法:

protected void onResume()
    {

        if (receiver == null)
        {
            receiver = new myBroadcastReceiver(); --> Here I call the receiver from another package
        }
        registerReceiver(reciever, new IntentFilter("SendMessage"));

    }

    @Override
    protected void onPause()
    {
        super.onPause();
        unregisterReceiver(reciever);
    }

在另一个包中,但在一个项目中,我为接收意图创建了 myBroadcastReceiver 类:

public class myBroadcastReceiver extends BroadcastReceiver 
{

    @Override
    public void onReceive(Context context, Intent intent) {

        String status = intent.getStringExtra("STATUS");
        String job = intent.getStringExtra("JOB");
        String media = intent.getStringExtra("MEDIA");
        GameWorldExtension.job = job;
        GameWorldExtension.media = media;
        GameWorldExtension.status = status;
        Log.d("receiver", "Got message: " + GameWorldExtension.status);
    }

}

我试过了,效果很好。现在我想尝试发送到另一个应用程序。我尝试了很多方法,但都没有成功。有人知道如何按正确的顺序发送吗?谢谢

4

1 回答 1

3

我认为这篇文章可以帮助你。有一个监听“onWifiChange”事件的 BroadcastReceiver 的例子。 如何在 Android 的不同应用程序中使用广播接收器?

- - - - 添加

在发件人方面:

1)发件人类:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent("pacman.intent.action.BROADCAST");
    intent.putExtra("message","Wake up.");
    sendBroadcast(intent);
}

在接收方:

1)接收器类:

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Message at Pacman received!");
    }
}

2)接收器清单文件:

<receiver android:name="com.ex.myapplication2.MyBroadcastReceiver">
    <intent-filter>
        <action android:name="pacman.intent.action.BROADCAST" />
    </intent-filter>
</receiver>
于 2013-10-18T07:52:31.720 回答