Check WiFi and GPS isConnected or Not in Android?

前端 未结 4 1117
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 02:17

I would need to check the wifi is on or off in the phone at the runtime?

if it is not connected, i want to show dialog and goto directly Setting/Wireless Controls to

相关标签:
4条回答
  • 2020-12-03 02:44

    You can use the WifiManager class to get the state of Wi-Fi.

    See this question for opening Wi-Fi settings. And this question for GPS status.

    0 讨论(0)
  • 2020-12-03 02:51
    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
    //mobile
    State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
    
    //wifi
    State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    
    0 讨论(0)
  • 2020-12-03 02:52

    To check if the device is connected via mobile or wifi you can use this code:

    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
    //mobile
    State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
    
    //wifi
    State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    

    and then use it like that:

    if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
        //mobile
    } else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
        //wifi
    }
    
    0 讨论(0)
  • 2020-12-03 03:02
    private boolean isNetworkAvailable() {
        ConnectivityManager connManager = (ConnectivityManager) 
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connManager.getActiveNetworkInfo();
        return activeNetworkInfo.isConnected();
    }
    
    public void onClick(DialogInterface dialog, int id) {
        // ...
        if (isNetworkAvailable()) {
            t3.setText("The Internet is available");
        } else {
            t3.setText("internet is not available");
        }
    }
    
    0 讨论(0)
提交回复
热议问题