Reputation: 13
I have list of apps. I want when user removed any app then refresh app list. Whats best way to do that? I search and found solution using Broadcast Receiver, is it best way? or are there exists direct way to do this? Can I capture the result of Action Remove intent?
Upvotes: 1
Views: 1291
Reputation: 11632
First you should add listener for that event like below, If you only interested only in remove just add that only,
<receiver
android:name=".receiver.AppStateReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
<data android:scheme="package" />
</intent-filter>
</receiver>
then you can add the broadcast receiver like this,
public class AppStateReceiver extends BroadcastReceiver {
public AppStateReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String packageName = intent.getData().getEncodedSchemeSpecificPart();
// Check if the application is install or uninstall and display the message accordingly
if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
} else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
intent.setAction(intent.getAction());
Intent uninstallIntent = new Intent();
uninstallIntent.setAction("Uninstall");
uninstallIntent.putExtra("packageName", packageName);
LocalBroadcastManager.getInstance(context).sendBroadcast(uninstallIntent);
} else if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
// Application Replaced
// toastMessage = "PACKAGE_REPLACED: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString(), PackageManager.GET_UNINSTALLED_PACKAGES);
} else if (intent.getAction().equals("android.intent.action.QUERY_PACKAGE_RESTART")) {
}
}
}
When you get the call back in ur receiver just send one local broadcast and you can listen to your Activity or Fragment or service and handle based on that.
Local broadcast listener in your fragment,
BroadcastReceiver UninstallReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateItems();
}
};
register and unregister the broadcast
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(UninstallReceiver);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UninstallReceiver, new IntentFilter("Uninstall"));
Upvotes: 2