AIM
Here is what I want to do:
- Check for internet connection at all the times in all the activities of my application (I have like 13 activities so far).
- If net is working then all is fine.
- If net is not working, show a message (using RelativeLayout) which will be displayed WHILE user is offline i.e. until net works again, that message will be there (on whatever activity user goes to)
Previous Attempts
Here is what I tried:
- I tried to create a class that extends
Broadcast Receiver
. I created an object of that class on all the activities and registered the receiver. - In my class, whenever net status changes, the main class sends a message through Intent to activity and then activity receives and checks the message (Code is below).
Here is the problem:
I never unregistered receiver which of course gave me an error.
Are you missing a call to unregisterReceiver()?
If I unregistered the receiver, it gave me following error:
java.lang.IllegalArgumentException: Receiver not registered
Code in Activites
// The onCreate function (Just a sample)
onCreate(){
registerReceiver(broadcastReceiver, new IntentFilter("broadCastName"));
}
// Outside OnCreate
NetworkStatus broadcastReceiver = new NetworkStatus() {
@Override
public void onReceive(Context context, Intent intent) {
String message;
Bundle b = intent.getExtras();
message = b.getString(KEY_NET_MESSAGE);
if (message.equals(KEY_NET_DISCONNECTED)){
Toast.makeText(SignupActivity.this, MESSAGE_NET_DISCONNECTED, Toast.LENGTH_SHORT).show();
btnSignup.setEnabled(false);
Network_disconnection.setVisibility(View.VISIBLE);
}
if (message.equals(KEY_NET_CONNECTED)){
btnSignup.setEnabled(true);
Network_disconnection.setVisibility(View.INVISIBLE);
}
}
};
//onStop, just a sample
@Override
protected void onStop() {
unregisterReceiver(broadcastReceiver);
super.onStop();
}
AndroidManifest.xml
<receiver android:name=".Common.NetworkStatus">
-
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
NetworkStatus.java
public class NetworkStatus extends BroadcastReceiver implements Keys.UniversalKeys{
@Override
public void onReceive(Context context, Intent arg1) {
boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(isConnected){
Intent i = new Intent("broadCastName");
// Data you need to pass to activity
i.putExtra(KEY_NET_MESSAGE, KEY_NET_DISCONNECTED);
context.sendBroadcast(i);
}
else{
Intent i = new Intent("broadCastName");
// Data you need to pass to activity
i.putExtra(KEY_NET_MESSAGE, KEY_NET_CONNECTED);
context.sendBroadcast(i);
Toast.makeText(context, KEY_NET_CONNECTED, Toast.LENGTH_LONG).show();
}
}
}
Question
What am I doing wrong? One thing is clear to me that maybe I should not create new receiver on each activity! Also, why do I need to make an extra java file? I mean why I just can't create a BroadcastReceiver object on each activity and go on with it?