Android 监听程序的安装和卸载
有些时候,需要监听到程序是否安装或者卸载成功,在android系统中,安装和卸载都会发送广播,当应用安装完成后系统会发android.intent.action.PACKAGE_ADDED广播。可以通过intent.getDataString()获得所安装的包名。当卸载程序时系统发android.intent.action.PACKAGE_REMOVED广播。同样intent.getDataString()获得所卸载的包名。
所以,只需要自定义一个BroadcastReceiver,来对系统广播进行监听和处理。
1、自定义广播
自定义广播MyInstalledReceiver继承自BroadcastReceiver,实现其onReceive()方式,具体代码如下:
[html]
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
//接收安装广播
if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
String packageName = intent.getDataString();
System.out.println("安装了:" +packageName + "包名的程序");
}
//接收卸载广播
if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
String packageName = intent.getDataString();
System.out.println("卸载了:" + packageName + "包名的程序");
}
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
//接收安装广播
if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
String packageName = intent.getDataString();
System.out.println("安装了:" +packageName + "包名的程序");
}
//接收卸载广播
if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
String packageName = intent.getDataString();
System.out.println("卸载了:" + packageName + "包名的程序");
}
}
} 2、注册监听
1) xml 方式:在AndroidManifest.xml 配置文件的Application节点下,添加自定义的注册监听 MyInstalledReceiver,在AndroidManifest.xml 添加的注册监听,其生命周期默认是整个应用的生命周期。
[html]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.apk"
android:versionCode="1"
android:versionName="1.0" >
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
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=".MyInstalledReceiver" >
<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>
<uses-sdk android:minSdkVersion="3" />
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.apk"
android:versionCode="1"
android:versionName="1.0" >
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
 
补充:移动开发 , Android ,