安卓应用的安装与卸载监听方法

移动开发 waitig 575℃ 百度已收录 0评论

对于安卓应用,在安装与卸载时,系统都会发出对应测广播,我们要做的就是注册相应的广播,在广播的onReceiver()方法中处理我们想要做的逻辑。
具体如下:
1.在MainActivity的onCreate()方法中动态注册广播:
安装对应的Action为:android.intent.action.PACKAGE_ADDED;
卸载对应的Action为:android.intent.action.PACKAGE_REMOVED;

//监听安装与卸载的广播
installedReceiver = new BootReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(“android.intent.action.PACKAGE_ADDED”); //安装
filter.addAction(“android.intent.action.PACKAGE_REMOVED”); //卸载
filter.addDataScheme(“package”);
this.registerReceiver(installedReceiver, filter);

2.写一个类继承自BroadCastReceiver,然后在需要重写的onReceiver()方法中写自己的逻辑:

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();    
          Log.d(TAG, "安装了新应用="+packageName);
          Toast.makeText(context, "安装了新应用="+packageName, Toast.LENGTH_SHORT).show();
          mlistAppInfo=queryAppInfo();
          Log.d(TAG, "mlistAppInfo-size="+mlistAppInfo.size());
          adapter.setData(mlistAppInfo); //将变更后的数据给到adapter
          adapter.notifyDataSetChanged();
      }    
      //接收卸载广播   
      if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {    
          String packageName = intent.getDataString();    
          Log.d(TAG, "卸载了应用="+packageName);
          Toast.makeText(context, "卸载了新应用="+packageName, Toast.LENGTH_SHORT).show();              
          mlistAppInfo=queryAppInfo();
            //删除数据库中对应的数据行
          String[]  mStr=packageName.split(":");
           int  res= mOperateDb.deleteApp(mStr[1]);
           Log.d(TAG, "删除了数据库中数据 id="+res);

          Log.d(TAG, "mlistAppInfo-size="+mlistAppInfo.size());
          adapter.setData(mlistAppInfo);
          adapter.notifyDataSetChanged();
      } 
  } 

}

3.在OnDestroy()中进行解注册:
@Override
protected void onDestroy() {

  if(installedReceiver!=null) {
    unregisterReceiver(installedReceiver);
   }

  super.onDestroy();
}

本文由【waitig】发表在等英博客
本文固定链接:安卓应用的安装与卸载监听方法
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)