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 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 ?