public class NetworkConnectionChangeReceiver extends BroadcastReceiver { private static final String TAG = NetworkConnectionChangeReceiver.class.getSimpleName(); private Context mContext; @Override public void onReceive(Context context, Intent intent) { mContext = context; ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo mobileNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(activeNetInfo != null) { Toast.makeText(context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); Log.e(TAG, "activeNetInfo.isAvailable(): " + activeNetInfo.isAvailable()); Log.e(TAG, "activeNetInfo.isConnected()(): " + activeNetInfo.isConnected()); } if(mobileNetInfo != null) { Toast.makeText(context, "Mobile Network Type : " + mobileNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); Log.e(TAG, "mobNetInfo.isAvailable(): " + mobileNetInfo.isAvailable()); Log.e(TAG, "mobNetInfo.isConnected()(): " + mobileNetInfo.isConnected()); } if(wifiNetInfo != null) { Toast.makeText(context, "Wifi Network Type : " + wifiNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); Log.e(TAG, "wifiNetInfo.isAvailable(): " + wifiNetInfo.isAvailable()); Log.e(TAG, "wifiNetInfo.isConnected()(): " + wifiNetInfo.isConnected()); } } }設成broadcast receiver是為了
在這個app中,當網路狀態一改變就會知道。
在AndroidManifest.xml裡加上
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>; <receiver android:name="com.example.test.receiver.NetworkConnectionChangeReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </receiver>
沒有留言:
張貼留言