2017-09-27 136 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

好的等待我会回复您 –

相关问题