手机当完成联网时会发送一个广播,我们只要创建一个广播接收者即可,代码如下:
package com.example.NetworkChangeReceiver2; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * Created by Heyiyong on 2014-4-20 下午2:23. */ public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NetworkInfo.State wifiState = null; NetworkInfo.State mobileState = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); if (NetworkInfo.State.CONNECTED == wifiState) { Toast.makeText(MyActivity.instance, "wifi连接成功!",1).show(); return; } if (NetworkInfo.State.CONNECTED == mobileState) {//当前的connect不是wifi,并且是移动数据 Toast.makeText(MyActivity.instance, "移动数据流量连接!",1).show(); return; } if (NetworkInfo.State.CONNECTED != wifiState && NetworkInfo.State.CONNECTED != mobileState) {//两种都不是 Toast.makeText(MyActivity.instance, "没有连接任何网络!",1).show(); } } }
MyActivity.java
package com.example.NetworkChangeReceiver2; import android.app.Activity; import android.os.Bundle; public class MyActivity extends Activity { public static MyActivity instance; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); instance = this; } }
注意:不要忘了添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
注册广播接收者:
<receiver android:name=".NetworkChangeReceiver" android:label="NetworkConnection" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver>