天天看點

Android 判斷網絡狀态,并且在沒有網絡的時候,打開網絡設定對話框

在使用Android連接配接網絡的時候,并不是每次都能連接配接到網絡,在這個時候,我們最好是在程式啟動的時候對網絡的狀态進行一下判斷,如果沒有網絡則進行即時提醒使用者進行設定。

要判斷網絡狀态,首先需要有相應的權限,下面為權限代碼:

即允許通路網絡狀态:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

下面為判斷代碼:

代碼

private boolean NetWorkStatus() {

boolean netSataus = false;

ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

cwjManager.getActiveNetworkInfo();

if (cwjManager.getActiveNetworkInfo() != null) {

netSataus = cwjManager.getActiveNetworkInfo().isAvailable();

}

if (netSataus) {

Builder b = new AlertDialog.Builder(this).setTitle("沒有可用的網絡")

.setMessage("是否對網絡進行設定?");

b.setPositiveButton("是", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

Intent mIntent = new Intent("/");

ComponentName comp = new ComponentName(

"com.android.settings",

"com.android.settings.WirelessSettings");

mIntent.setComponent(comp);

mIntent.setAction("android.intent.action.VIEW");

startActivityForResult(mIntent,0); // 如果在設定完成後需要再次進行操作,可以重寫操作代碼,在這裡不再重寫

}).setNeutralButton("否", new DialogInterface.OnClickListener() {

dialog.cancel();

}).show();

return netSataus;

通過上面的代碼即可完成對網絡狀态的判斷!

      本文轉自xyz_lmn51CTO部落格,原文連結:http://blog.51cto.com/xyzlmn/818164,如需轉載請自行聯系原作者

繼續閱讀