Skip to content

Instantly share code, notes, and snippets.

@kojiokb
Created August 22, 2012 11:30
Show Gist options
  • Save kojiokb/3424667 to your computer and use it in GitHub Desktop.
Save kojiokb/3424667 to your computer and use it in GitHub Desktop.
ネットワークの接続・切断を検知して処理を行う
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class ConnectivityReceiver extends BroadcastReceiver {
/*
* AndroidManifest.xml
*
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
*
* <receiver android:name=".ConnectivityReceiver" >
* <intent-filter>
* <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
* </intent-filter>
* </receiver>
*/
private final String TAG = getClass().getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "ConnectivityReceiver#onReceive()");
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
// 切断時の処理
return;
}
Log.e(TAG, "NetworkInfo#isConnected() : " + networkInfo.isConnected());
if (networkInfo.isConnected()) {
// 接続時の処理
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment