简体   繁体   中英

How to active Broadcast Receiver only when APP is in background in android?

I am using Broadcast Receiver in my app which is active when app is open as well as app in close.what I want is to active this Broadcast Receiver only when app is open and also on specific activity.

here is my

public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    // Check if the application is install or uninstall and display the message accordingly
    if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
        // Application Install
        Log.e("Package Added:-", intent.getData().toString());

    } else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {

        Log.e("Package Removed:-", intent.getData().toString());
    } else if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
        Log.e("Package Replaced:-", intent.getData().toString());
    }


}

For example :

@Override
protected void onPause () {

    // Unregister since the activity is not visible
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    super.onPause();
}

@Override
protected void onResume () {
    super.onResume();

    // Register mMessageReceiver to receive messages.
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
                                                             new IntentFilter(
                                                                     YourBroadcastReceiver.class
                                                                             .getSimpleName()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM