android中 檢查 網絡連接狀態的變化,無網絡時跳轉到設置界面

1:
在AndroidManifest.xml中加一個聲明


<receiver android:name="NetCheckReceiver">
    <intent-filter>
           <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>




NetCheckReceive.java文件如下


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;


public class NetCheckReceiver extends BroadcastReceiver{


    //android 中網絡變化時所發的Intent的名字
    private static final String netACTION="android.net.conn.CONNECTIVITY_CHANGE";
    @Override
    public void onReceive(Context context, Intent intent) {


        if(intent.getAction().equals(netACTION)){
    //Intent中ConnectivityManager.EXTRA_NO_CONNECTIVITY這個關鍵字表示着當前是否連接上了網絡
    //true 代表網絡斷開   false 代表網絡沒有斷開
            if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)){
                aActivity.stopFlag = true;
            }else{
                aActivity.stopFlag = false;
            }
        }
    }
}


aActivity.stopFlag 是一個static布爾值  可以出現在程序需要判斷網絡情況的地方。




2順便加一個不需要broadcastReceiver就可以查看網絡的例子。
這個方法可以放在需要檢查網絡通訊情況的地方。返回值爲true代表網絡暢通。
 private boolean checkNetwork() {
        ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo net = conn.getActiveNetworkInfo();
        if (net != null && net.isConnected()) {
            return true;
        }
        return false;
    }




以下的這個判斷可以使用戶在失去網絡鏈接的情況下,自動跳轉到設置無線網界面。
        if (!checkNetwork()) {
            Toast.makeText(this, R.string.lose_network, Toast.LENGTH_LONG).show();
            Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
            startActivity(intent);
            return;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章