我正在从app向app发送广播。要将我的代码升级到Android O,我已将隐式广播转换为显式,但它无效

问题描述 投票:1回答:1

接收应用的Manifest.xml。

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver android:name=".DemoReceiver"
        android:exported="true" android:enabled="true">
        <intent-filter>
            <action android:name="com.example.myparentapplication.demo"/>
        </intent-filter>
</receiver>

接收应用程序中声明的接收者:

public class DemoReceiver extends BroadcastReceiver {

public DemoReceiver(){}

@Override
public void onReceive(Context context, Intent intent) {
    Log.v(TAG, "Received");

    String data = intent.getStringExtra("data");
    Toast.makeText(context,"opening the intent data : " + data,Toast.LENGTH_LONG ).show();
  }
}

广播应用发送的广播:

Intent intent = new Intent("com.example.myparentapplication.demo");
            intent.putExtra("data","job dispatched");
            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), "com.example.myparentapplication.DemoReceiver"));
            sendBroadcast(intent);

这样我将api升级到Android'O'后就会使用广播,但我没有收到任何广播。在文档中它表示显式广播允许在Android Oreo之后在清单中注册。请指导我这里有什么问题?注意:接收应用是一个后台应用。所以我无法动态注册广播。我已经尝试了几乎所有的堆栈溢出解决方案,但它仍然无法正常工作。

android android-intent android-broadcast android-broadcastreceiver
1个回答
1
投票
intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), "com.example.myparentapplication.DemoReceiver"));

getApplicationContext().getPackageName()将返回发送应用程序的应用程序ID。您的ComponentName需要接收应用程序的应用程序ID。

© www.soinside.com 2019 - 2024. All rights reserved.