12月 102019
一、Android8.0之前的版本
在Android8.0之前,可以通过注册静态广播来监听应用安装或者删除的广播
如下是在AndroidManifest.xml中注册静态广播的一段代码
1 2 3 4 5 6 7 8 9 |
<receiver android:name=".MyReceiver"> <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED" /> <action android:name="android.intent.action.PACKAGE_REMOVED" /> <action android:name="android.intent.action.PACKAGE_REPLACED" /> <data android:scheme="package" /> </intent-filter> </receiver> |
唯一需要注意的是,有一个android:scheme属性是必须的,否则收不到广播
二、Android8.0之后的版本
Android8.0之后很多静态广播不能用了,想要接收应用安装、覆盖安装和删除的广播,需要动态注册广播。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_REPLACED); filter.addDataScheme("package"); registerReceiver(mReceiver, filter); } @Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } BroadcastReceiver mReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Toast.makeText(MainActivity.this, action, Toast.LENGTH_SHORT).show(); } }; } |
Sorry, the comment form is closed at this time.