接收应用的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之后在清单中注册。请指导我这里有什么问题?注意:接收应用是一个后台应用。所以我无法动态注册广播。我已经尝试了几乎所有的堆栈溢出解决方案,但它仍然无法正常工作。
intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), "com.example.myparentapplication.DemoReceiver"));
getApplicationContext().getPackageName()
将返回发送应用程序的应用程序ID。您的ComponentName
需要接收应用程序的应用程序ID。