在Android開發中,如果該應用程序需要連接網絡請求,那么最好我們先做一個檢測網絡是否在線的判斷,否則程序容易出現卡死或FC等Bug,應該判斷如果手機離線則彈出提示讓用戶檢查網絡,如果正常則繼續執行請求。
Android檢測網絡的方法:
在提交網絡請求時執行該方法即可,如果檢測到網絡沒有連接好,則會彈出提示框:“抱歉,目前無法連接網絡。請檢查您的手機網絡連接!”並帶有打開網絡設置的按鈕選項。
private boolean goToNetWork() {
// TODO Auto-generated method stub
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info == null || !info.isAvailable()){
new AlertDialog.Builder(this).setTitle("提醒:").setMessage("抱歉,目前無法連接網絡。\n請檢查您的手機網絡連接!").setPositiveButton("打開網絡設置",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent=null;
//判斷手機系統的版本 即API大於10 就是3.0或以上版本
if(android.os.Build.VERSION.SDK_INT>10){
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
startActivity(intent);
}
}).setNegativeButton("聯知道了!",null).show();
return false;
}
else{
//new AlertDialog.Builder(this).setMessage("網絡正常可以使用").setPositiveButton("Ok", null).show();
return true;
}
調用方法:
if(goToNetWork()){<!–要繼續執行的代碼–>}
-完-
