2017-09-27 138 views

回答

1

創建一個類nameed CheckConnection爲波紋管

比你調用這個類,你要檢查可用的Internet連接或不

代碼

public class ConnectionCheck { 

    public boolean isNetworkConnected(Context context) { 
     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo ni = cm.getActiveNetworkInfo(); 
     if (ni == null) { 
      // There are no active networks. 
      return false; 
     } else 
      return true; 
    } 

    public AlertDialog.Builder showconnectiondialog(Context context) { 

     final AlertDialog.Builder builder = new AlertDialog.Builder(context) 
       .setIcon(R.mipmap.ic_launcher) 
       .setTitle("Error!") 
       .setCancelable(false) 
       .setMessage("No Internet Connection.") 
       .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
        } 
       }); 

     return builder; 
    } 
} 

呼叫上面的類,你想檢查互聯網連接:如上線

ConnectionCheck connectionCheck = new ConnectionCheck(); 
     if (connectionCheck.isNetworkConnected(this)){// or your context pass here 
      //operation you want if connection available 
     }else { 
      connectionCheck.showconnectiondialog(this); //context pass here 
     } 

而且你必須訪問網絡狀態和互聯網中ManifestActivity.xml添加權限:

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

我不在每個活動中都不需要添加此代碼。我需要編寫一次代碼,並在突然發生變化時檢查互聯網連接。 – Shrirambaabu

+0

你如何監控網絡狀態? – CoXier

+0

好的等待我會回覆您 –

相關問題