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,其生命周期默认是整个应用的生命周期


    
        
            

            
        
    

    
        
            
            
            
        
    

 

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");
        }


    }
};

转载于:https://www.cnblogs.com/rookier/p/4877071.html

你可能感兴趣的:(移动开发)