I have written a broadcast receiver to detect installing and removing applications. But I want to get the name of installed or removed application too. How can I do that?
This is my BroadcastReceiver:
public class PackageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch(intent.getAction())
{
case Intent.ACTION_PACKAGE_ADDED:
String replaced = "";
if(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
{
replaced = "replaced";
}
Log.e("application", "installed " + replaced);
break;
case Intent.ACTION_PACKAGE_REMOVED:
if(!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
{
Log.e("application", "removed");
}
break;
}
}
}
In the manifest:
<receiver
android:name=".receivers.PackageReceiver"
android:enabled="true"
android:exported="true">
<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>
Combining info found in android documentation and this answer on stack overflow I came up with the following. Intents you are using might have EXTRA_UID extra which contains uid of modified app. With uid you can get the app name. However you can only do that on ACTION_PACKAGE_ADDED intent, because in ACTION_PACKAGE_REMOVED app was already remove and you cant get its name (you can still get uid).
Check this sample:
int uid = intent.getIntegerExtra(Intent.EXTRA_UID);
String appName = context.getPackageManager().getNameForUid(uid);
So in your case it would be:
public class PackageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch(intent.getAction())
{
case Intent.ACTION_PACKAGE_ADDED:
String replaced = "";
String appName = "";
int uid = -1;
if(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
{
replaced = "replaced";
}
uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
if(uid != -1){
appName = context.getPackageManager().getNameForUid(uid);
}
Log.e("application", "installed " + replaced + " uid " + uid + " appname " + appName);
break;
case Intent.ACTION_PACKAGE_REMOVED:
if(!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
{
Log.e("application", "removed");
}
break;
}
}
}
With this code I've seen this written in logcat after installing Google Earth from Google Play:
installed uid 10404 appname com.google.earth