Created
June 26, 2011 09:37
-
-
Save rajiv-singaseni/1047445 to your computer and use it in GitHub Desktop.
A sample activity monitoring the network connectivity of an android device
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.webile.network; | |
import android.app.Activity; | |
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.widget.Toast; | |
public class MainActivity extends Activity { | |
/** Called when the activity is first created. */ | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); | |
registerReceiver(networkStateReceiver, filter); | |
} | |
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() { | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); | |
if(!noConnectivity) { | |
onConnectionFound(); | |
} else { | |
onConnectionLost(); | |
} | |
} | |
}; | |
public void onConnectionLost() { | |
Toast.makeText(this, "Connection lost", Toast.LENGTH_LONG).show(); | |
} | |
public void onConnectionFound() { | |
Toast.makeText(this, "Connection found", Toast.LENGTH_LONG).show(); | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
unregisterReceiver(networkStateReceiver); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment