Check WiFi and GPS isConnected or Not in Android?

我只是一个虾纸丫 提交于 2019-12-17 10:48:11

问题


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 enable it by user.

its for both wifi and Gps staus of the phone. How to do it? which intent to wake for this? Any idea?


回答1:


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.




回答2:


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
}



回答3:


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");
    }
}



回答4:


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();


来源:https://stackoverflow.com/questions/2973290/check-wifi-and-gps-isconnected-or-not-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!