Do we have a way to trigger a custom API when user tries to uninstall the application?

890 Views Asked by At

Trying to open the Device Admin Access option when the user tries to uninstall the application from the settings->apps screen and trigger a custom API to notify that the user is trying to uninstall application from the settings->apps.

I'm able to get the uninstall event, open the Device Admin Access option and also able to trigger a custom API when uninstalling the application by doing a long press on the app icon and select uninstall but it is not the case when doing the uninstall from the settings->apps.

How to retrieve the event when user tries to uninstall the application anywhere in the mobile?

1

There are 1 best solutions below

0
Adnan On

It is not possible to directly trigger a custom API or call a specific function when an Android application is uninstalled. However, you can use a combination of BroadcastReceiver and PackageManager to detect when an application is uninstalled and then perform any necessary actions in response.

A BroadcastReceiver can be used to listen for the Intent.ACTION_PACKAGE_REMOVED action, which is broadcast when an application is removed from the device. Obviously it could be done in a different application than the one you are listening to for uninstallation. You can then use the PackageManager class to check the package name of the uninstalled application and determine if it is your application. Once you have determined that your application is being uninstalled, you can perform any necessary actions, such as sending a request to a custom API or saving user data.

public class PackageReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
            // Get the package name of the uninstalled application
            String packageName = intent.getData().getSchemeSpecificPart();
            // Check if the package name matches your package
            if (packageName.equals("com.example.mypackage")) {
                // Perform any necessary actions
                // ...
            }
        }
    }
}

You will also need to register the BroadcastReceiver in the AndroidManifest.xml file, so that it will receive the Intent.ACTION_PACKAGE_REMOVED action. You can do this by adding the following code to the tag in the AndroidManifest.xml file:

<receiver android:name=".PackageReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_REMOVED" />
        <data android:scheme="package" />
    </intent-filter>
</receiver>

It's also important to be aware that as of Android 11, apps can't register broadcast receivers for this action unless they hold the QUERY_ALL_PACKAGES permission which is a system-level permission that can only be obtained via a signature-level permission, which is granted to apps that are part of the firmware.