问题原因
Android
8.0后在AndroidManifest.xml
文件中静态注册广播接收失效的原因是官方对耗电量的优化,避免APP
滥用广播。
除了少部分的广播仍支持静态注册(如开机广播),其余的都会出现失效的情况。
解决方案
使用动态注册广播
MainActivity
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private AppStateReceiver appStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onStart(){
super.onStart();
appStateReceiver = new AppStateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PACKAGE_ADDED");
filter.addAction("android.intent.action.PACKAGE_REMOVED");
filter.addDataScheme("package");
this.registerReceiver(appStateReceiver, filter);
}
@Override
public void onDestroy(){
if(appStateReceiver != null) {
this.unregisterReceiver(appStateReceiver);
}
super.onDestroy();
}
}
AppStateReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AppStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("android.intent.action.PACKAGE_INSTALL".equals(action)){
String packageName = intent.getDataString();
System.out.println("安装了 :" + packageName);
}else if("android.intent.action.PACKAGE_REMOVED".equals(action)){
String packageName = intent.getDataString();
System.out.println("卸载了 :" + packageName);
}
}
}