第一步:写一个广播接收类
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast;
public class NetworkChangeBroadcast extends BroadcastReceiver { ? ? @Override ? ? public void onReceive(Context context, Intent intent) { ? ? ? ? Log.d("NetworkChangeBroadcast", "network changed!");
? ? ? ? boolean isNetworkAvailable = false, isWifiAvailable = false, isMobileAvailable = false; ? ? ? ? ConnectivityManager connectivityManager = (ConnectivityManager) ? ? ? ? ? ? ? ? context.getSystemService(Context.CONNECTIVITY_SERVICE); ? ? ? ? NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); ? ? ? ? if (networkInfo != null) { ? ? ? ? ? ? isNetworkAvailable = networkInfo.isAvailable(); ? ? ? ? ? ? isWifiAvailable = networkInfo.isAvailable() && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI); ? ? ? ? ? ? isMobileAvailable = networkInfo.isAvailable() && (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE); ? ? ? ? }
? ? ? ? if (isNetworkAvailable) { ? ? ? ? ? ? if (isWifiAvailable) { ? ? ? ? ? ? ? ? Toast.makeText(context, "当前网络状态:Wifi 可用", Toast.LENGTH_SHORT).show(); ? ? ? ? ? ? } else if (isMobileAvailable) { ? ? ? ? ? ? ? ? Toast.makeText(context, "当前网络状态:移动网络可用", Toast.LENGTH_SHORT).show(); ? ? ? ? ? ? } ? ? ? ? } else { ? ? ? ? ? ? Toast.makeText(context, "当前网络状态:网络不可用", Toast.LENGTH_SHORT).show(); ? ? ? ? } ? ? } }
第二步:在需要监控的类中引用,一般为activity的基类,动态注册广播监听网络的变化,在onCreate中注册,onDestroy中反注册
import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
public class BaseActivity extends AppCompatActivity {
? ? private NetworkChangeBroadcast networkChangeBroadcast = null;
? ? @Override ? ? protected void onCreate(Bundle savedInstanceState) { ? ? ? ? super.onCreate(savedInstanceState); ? ? ? ? setContentView(R.layout.activity_main);
? ? ? ? networkChangeBroadcast = new NetworkChangeBroadcast(); ? ? ? ? IntentFilter intentFilter = new IntentFilter(); ? ? ? ? intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); ? ? ? ? registerReceiver(networkChangeBroadcast, intentFilter); ? ? }
? ? @Override ? ? protected void onDestroy() { ? ? ? ? super.onDestroy(); ? ? ? ? unregisterReceiver(networkChangeBroadcast); ? ? } }
最后注意:访问网络状态需要在Manifest中添加网络访问权限? ? ? ? ?android.permission.ACCESS_NETWORK_STATE
|