Android8 自定义广播接收不到的问题
最近在用安卓广播的时候,按照流程进行操作,可是不管怎样都没有出现我接受的广播,网上查阅资料以后,发现在Android8中,如果是静态注册广播,需要在action中保留原来的静态广播,加入Component参数;代码如下:
AndroidMainifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.myapplication"> <!-- 权限 --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".BroadcastActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="com.example.administrator.myapplication.MyBroadcastReceiver"/> </intent-filter> </receiver> </application> </manifest>
MyBroadcastReceiver.java:
package com.example.administrator.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "收到广播了", Toast.LENGTH_LONG).show(); } }
BroadcastActivity.java:
package com.example.administrator.myapplication; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; public class BroadcastActivity extends AppCompatActivity { private MyBroadcastReceiver myBroadcastReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); //注册广播 myBroadcastReceiver = new MyBroadcastReceiver(); IntentFilter itFilter = new IntentFilter(); Button btn = (Button) findViewById(R.id.sendBtn); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent("com.example.administrator.myapplication.MyBroadcastReceiver"); //第一个参数为包的路径,第二个参数为类名 intent.setComponent(new ComponentName("com.example.administrator.myapplication", "com.example.administrator.myapplication.MyBroadcastReceiver")); sendBroadcast(intent); } }); } //注销的时候取消广播 public void onDestroy() { super.onDestroy(); unregisterReceiver(myBroadcastReceiver); } }