Android获取有关安装或删除的应用程序的广播

Co *_*der 2 android broadcastreceiver

我想开发一个应用程序,可以接收有关正在安装或删除的其他应用程序的广播.到目前为止,我尝试了下面的代码,但是,它仅在删除安装时提供广播事件,它不提供有关安装或删除的其他应用程序beibg的信息.那么,有没有办法获取新安装的应用程序的包名称.

在表现:

receiver android:name=".apps.AppListener">
    <intent-filter android:priority="100">
         <action android:name="android.intent.action.PACKAGE_INSTALL"/>
         <action android:name="android.intent.action.PACKAGE_ADDED"/>  
         <action android:name="android.intent.action.PACKAGE_REMOVED"/>
         <data android:scheme="package"/> 
    </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

在AppListener中:

public class AppListener extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
      // there is a broadcast event here
      // but how to get the package name of the newly installed application 
      Log.v(TAG, "there is a broadcast");
    }
}
Run Code Online (Sandbox Code Playgroud)

增加: 对于Api 14或更高版本,不推荐使用此功能.

     <action android:name="android.intent.action.PACKAGE_INSTALL"/> 
Run Code Online (Sandbox Code Playgroud)

Har*_*rry 6

包名称嵌入到您在onReceive()方法中接收的Intent中.您可以使用下面的代码段阅读它:

Uri data = broadcastIntent.getData();
String installedPackageName = data.getEncodedSchemeSpecificPart();
Run Code Online (Sandbox Code Playgroud)

对于PACKAGE_ADDED,PACKAGE_REMOVED和PACKAGE_REPLACED,您可以使用上面的代码获取包名称.

如果应用程序更新,您将获得2个背靠背广播,如下所示:1.PACKAGE_REMOVED 2. PACKAGE_REPLACED

在应用程序更新的情况下,PACKAGE_REMOVED意图将包含额外的布尔值,以区分应用程序删除和应用程序更新.您可以读取此布尔值,如下所示:

boolean isReplacing = broadcastIntent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Run Code Online (Sandbox Code Playgroud)

只是为了得到包名称,你正在调用PackageManagerService api是开销.必须避免它.

希望对你有帮助.