Reputation: 14648
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();
}
Upvotes: 3
Views: 2116
Reputation: 2624
You can create an Activity e.g. 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 ?
Upvotes: 3
Reputation: 20553
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.
Upvotes: 1
Reputation: 6108
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.
Upvotes: 1