简体   繁体   English

仅当APP在android中处于后台时如何激活广播接收器?

[英]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()));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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