java - 在 Android 中使用广播

标签 java android android-intent broadcastreceiver android-broadcast

有人知道如何将 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 );

我还添加了检查 Intent 的方法:

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 类来接收 Intent :

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

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

最佳答案

我认为这篇文章可以帮助你。有一个 BroadcastReceiver 的例子,它正在监听“onWifiChange”事件。 How to use Broadcast Receiver in different Applications in 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) 接收器 list 文件:

<receiver android:name="com.ex.myapplication2.MyBroadcastReceiver">
    <intent-filter>
        <action android:name="pacman.intent.action.BROADCAST" />
    </intent-filter>
</receiver>

关于java - 在 Android 中使用广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444276/

相关文章:

Android 模拟/发送 ACTION_MEDIA_BUTTON Intent

android - "Rotation Locker"是如何工作的?

java - PowerMock - @PrepareForTest 上的 NPE

java - 创建一个没有ActionBar的后退按钮

java - 将Arraylist添加到自定义对象不更新android中的值

java - Android MediaPlayer 在同时播放两种声音时有时会跳过或失败

android - 使用两个值从 AutoCompleteTextView 获取 ID

java - onStartLoading() 和forceLoad() 是在哪里调用和实现的?

java - 在 selenium 中使用 Internet Explorer 浏览器时无法启动 IE 浏览器 - IllegalStateException

Java:使用 nio Files.copy 移动目录