閱讀541 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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

在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布爾值 可以出現在程序需要判斷網絡情況的地方。

順便加一個不需要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;
        }


最後更新:2017-04-02 17:51:24

  上一篇:go 利用c#製作托盤程序,並禁止多個應用實例運行
  下一篇:go 最近在使用MyEclipse的SVN插件時總是彈出一個大大的對話框,報一個Failed to load JavaHL Library.錯誤