1姜胖、定義一個類,假設(shè)為StateBroadcastReceiver繼承BroadcastReceiver胆胰,然后重寫onReceive方法:
@Override
public voidonReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
State wifiState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();//獲取wifi網(wǎng)絡(luò)狀態(tài)
State mobileState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();//獲取移動數(shù)據(jù)網(wǎng)絡(luò)狀態(tài)
//沒有執(zhí)行return,則說明當前無網(wǎng)絡(luò)連接
if(wifiState != State.CONNECTED&& mobileState != State.CONNECTED) {
System.out.println("------------> Network is validate");
intent.setClass(context, NetWorkErrorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return;
}
//判斷網(wǎng)絡(luò)是否已經(jīng)連接
System.out.println("------------> Network is ok");
}
2伏嗜、在Manifest文件中注冊廣播
<receiver?android:name=".StateBroadcastReceiver" >
? ? ? <intent-filter>
? ? ? ? ? ? android:name="android.net.conn.CONNECTIVITY_CHANGE" />
? ? ? </intent-filter>
</receiver>
3、別忘了加權(quán)限