创建一个java 类 MyInstalledReceiver,继承BroadcastReceiver
package com.meefo.fengweihezi_android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyInstalledReceiver 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 + "包名的程序");
}
}
}
到AndroidManifest xml文件里注册广播地址
<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>
Activity里重写MyInstalledReceiver的onReceiver方法
private final MyInstalledReceiver installedReceiver = new MyInstalledReceiver(){
@Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
// String packageName = intent.getDataString();
//这里就可以写你想写的动作了。这里相当于是一个软件安装完成的回调
}
}
};
定义一个初始化方法,然后在程序框架初始化的位置调用这个方法
private void registerSDCardListener(){
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
intentFilter.addDataScheme("package");
registerReceiver(installedReceiver, intentFilter);
}