2011-08-23 13 views
0

現在、インターネットが有効になっていないとアプリがクラッシュします。私は例外をキャッチし、私のポップアップダイアグラム(以下)を表示して、データを元に戻す方法を知りたかったのです。私はこのような電話の状態を確認します: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