public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(isNetworkAvailable(this)){ //有网的情况 Toast.makeText(MainActivity.this,"网络可用",Toast.LENGTH_SHORT).show(); }else{ //没网的情况,提示去手动开启网络 Toast.makeText(MainActivity.this,"网络不可用",Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder=new AlertDialog.Builder(this) .setTitle("提示") .setMessage("当前网络不可用,是否去设置网络") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent=new Intent("android.settings.WIFI_SETTINGS"); startActivity(intent); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); builder.create().show(); } } @Override public void onClick(View v) { } //判断网络是否连接的方法 public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 当前网络是连接的 if (info.getState() == NetworkInfo.State.CONNECTED) { // 当前所连接的网络可用 return true; } } } return false; } } 注意:别忘了加权限<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Android-----------判断是否有网络连接并手动开启网络
最新推荐文章于 2024-03-13 00:27:17 发布