你的位置:首页 > 操作系统

[操作系统]小记:判断设备是否联网!


记住加权限:

 1 package com.lixu.getInternet; 2  3 import android.app.Activity; 4 import android.content.Context; 5 import android.net.ConnectivityManager; 6 import android.net.NetworkInfo; 7 import android.os.Bundle; 8 import android.widget.Toast; 9 10 public class MainActivity extends Activity {11 12   @Override13   protected void onCreate(Bundle savedInstanceState) {14     super.onCreate(savedInstanceState);15     setContentView(R.layout.activity_main);16 17     boolean b = isConnect(this);18 19     if (b == true)20       Toast.makeText(this, "您的手机已经联网!", Toast.LENGTH_LONG).show();21 22     else if (b == false)23       Toast.makeText(this, "您的手机没有联网!", Toast.LENGTH_LONG).show();24 25   }26 27   public boolean isConnect(Context context) {28     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);29     if (cm != null) {30       NetworkInfo info = cm.getActiveNetworkInfo();31       if (info != null && info.isConnected()) {32         if (info.getState() == NetworkInfo.State.CONNECTED) {33           return true;34         }35       }36     }37     return false;38   }39 40 }

运行效果: