android程序的安装与卸载

时间:2023-03-09 03:06:31
android程序的安装与卸载

Android

android在安装应用程序与卸载应用程序时都会发送广播,安装应用程序成功时会发送android.intent.action.PACKAGE_ADDED广播,可以通过intent.getDataString()获取安装应用的包名。当卸载应用程序成功时,系统会发送android.intent.action.PACKAGE_REMOVED广播,同样可以通过intetn.getDataString()获取应用的包名。

所以需要自定义一个BroadcastReceiver来对系统广播进行监听与处理。

1、自定义广播
自定义AppChangeTestReceiver继承自BroadcastReceiver,实现其onReceive()方式,具体代码如下。

public class AppChangTestReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction(); if(Intent.ACTION_PACKAGE_ADDED.equals(action)) {
Log.i("AAA",">>>>>>>>>>>>>>>>>>>package added"); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Log.i("AAA",">>>>>>>>>>>>>>>>>>>package removed");
}
}
}

2、注册监听
1)XML方式:在AndroidManifest.xml的配置文件Application节点下,注册自定义的AppChangeTestReceiver,其生命周期默认是整个应用的生命周期

<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <receiver android:name=".receiver.AppChangTestReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
</application>
</manifest>

2)代码中动态注册:一般在Activity的onStart()方法中进行注册,在onStop或者在onDestroy方法中进行注销,其生命周期是Activity的生命周期。

   @Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
registerReceiver(mReceiver, intentFilter);
} @Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
} private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction(); if(Intent.ACTION_PACKAGE_ADDED.equals(action)) {
Log.i("AAA","####################-------package added"); } else if(Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Log.i("AAA","###################----------package removed");
} }
};