简体   繁体   中英

broadcast receiver not active when app in background

I have a broadcast receiver registered through manifest file. Basically, it activates when internet connection is on/off. It display Toast when it come on and also when it goes off.

However, I dont want this Toast to be displayed when my app in the background (a home button is pressed). How can I do that? I dont mind if the broadcast is still registered but I need a way to know my app is not visible so I disable the Toast.

Thank you very much

    ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo active_nwInfo = (NetworkInfo) connManager.getActiveNetworkInfo();

if(active_nwInfo == null || !active_nwInfo.isConnected()) {
            //broadcast.putExtra("action", "no_connection");
            Toast.makeText(context, "No Internet Connection", Toast.LENGTH_LONG).show();


        }else {
            //broadcast.putExtra("action", "new_connection");
            Toast.makeText(context, "Internet Connection", Toast.LENGTH_LONG).show();


        }

You can create an Activity eg BaseActivity (which extends Activity ofcourse). In onResume() and onPause() methods of this Activity , you can set a boolean variable as Anup Cowkur has done in his answer.

Now you can extend all your activities from BaseActivity instead of Activity class. So in onReceive() function of your BroadcastReceiver , you can first check this boolean variable and show Toast only when it is "true".

These links are quite helpful :

Checking if an Android application is running in the background

Why BroadcastReceiver works even when app is in background ?

In your activity, unregister your receiver at onPause(), and register it again at onResume()

@Override
protected void onPause() {
    mLocalBroadcastManager.unregisterReceiver(mReceiver);
    super.onPause();
}

@Override
protected void onResume() {
    mLocalBroadcastManager.registerReceiver(mReceiver, filter);
    super.onResume();
}

I am just using LocalBroadcastManager for demo, change it to whichever that suits your receiver.

Use a boolean flag to indicate whether app is in background or not:

boolean appIsInBackgorund = false;
  @Override
    protected void onPause() {
        appIsInBackgorund = true;
        super.onPause();
    }

    @Override
    protected void onResume() {
        appIsInBackgorund = false;
        super.onResume();
    }

Now, you can check this flag to determine if the app is in background state and determine whether to display or not display your toast.

If you need the same flag in more than one activity, you can store it in SharedPreferences .

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