2011-08-23 14 views
0

目前我的应用程序崩溃,如果没有启用互联网。我想知道如何捕捉异常,并显示我的popupdialog(下面),以便他们可以导航以重新打开数据。我检查这样的电话状态:Android:捕捉异常,如果移动数据未启用

public void CheckInternet() 
{ 
    ConnectivityManager connec = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); 
    android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

    // Here if condition check for wifi and mobile network is available or not. 
    // If anyone of them is available or connected then it will return true, otherwise false; 

    if (wifi.isConnected()) { 

    } else if (!mobile.isConnected()) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage("You need to enable mobile data in order to use this application:") 
       .setCancelable(false) 
       .setPositiveButton("Turn on Data", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.cancel(); 
         Intent newintent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); 
         startActivity(newintent); 


        } 
       }) 
       .setNegativeButton("Exit", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         Main.this.finish(); 
        } 
       }); 
     AlertDialog alert = builder.show(); 
    } else if (mobile.isConnected()) { 
     //nothing 
    } 
} 

而我在onCreate()的开头调用函数。

在此先感谢!

回答

1

您可以创建这个布尔方法,并调用它时,你需要做一些事情需要网络连接:

public boolean isOnline() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
     return true; 
    } 
    return false; 
} 

而且例子可能是以下几点:

if (isOnline()) { 
    // Do network stuff 
} else { 
    // Show network error 
} 
+0

谢谢,我没有使用你的代码,但你的想法。我在检查中使用互联网包裹了我的功能,它效果很好!再次感谢。 – Nick