判断数据连接----小程序
package com.example.testnet; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.Toast; public class Btn1Listener implements OnClickListener { private Context context;private ConnectivityManager cm;
public Btn1Listener(Context context){ //建立一个上下文构造器 this.context = context; } @Override public void onClick(View v) { Activity c =(Activity)context; cm = (ConnectivityManager) c.getSystemService(c.CONNECTIVITY_SERVICE); //主要代码 NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo==null){ //没数据要执行的方法 Toast ts = Toast.makeText(context, "你当前没有数据连接",Toast.LENGTH_SHORT); ts.setGravity(Gravity.CENTER, 0, 0); ts.show(); } else{ //有数据的时候的方法 Toast ts = Toast.makeText(context,"你当前数据在连接", Toast.LENGTH_SHORT); ts.setGravity(Gravity.CENTER,0,0); ts.show(); } } }
在AndroidManifest.xml 文件添加以下权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>