zoukankan      html  css  js  c++  java
  • 验证是否有网络

    一、布局的代码:

    <TextView
    android:id="@+id/textViews"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/networktrue"
    />

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/buttons"
    android:layout_below="@id/textViews"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:text="@string/ifnetwork"
    />

    二、布局的效果图

      

    三、点击“是否有网络这个按钮”可以测试到当前网络是否正常,如下这个是实现这个验证是否有网络的代码

    public class Test implements OnClickListener{

    private Context context;
    private TextView tv;
    private ConnectivityManager cm;//这个是用来封装连接网络

    public Test(Context context){
    this.context = context;
    }
    @Override
    public void onClick(View v) {

    Activity c = (Activity)context;
    //关联到这个提示控件
    tv = (TextView) c.findViewById(R.id.textViews);
    String netStatus;//这个是用来封装网络是否正常
    int color;//这个是用来封装色体
    cm = (ConnectivityManager) c.getSystemService(c.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if(netInfo==null){
    //提示没有网络
    netStatus = c.getResources().getString(R.string.netStatus0);
    color = c.getResources().getColor(R.color.red);
    }else{
    //不需提示
    netStatus = c.getResources().getString(R.string.netStatus1);
    color = c.getResources().getColor(R.color.green);
    }
    tv.setText( netStatus );
    tv.setBackgroundColor(color);
    }

    }

    ---------------------------------------------------------------------------------

    public class MainActivity extends Activity {

    private Button tstNetwrkBt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    /*tstNetwrkBtn = (Button) findViewById(R.id.tstNetwrkBtn);
    tstNetwrkBtn.setOnClickListener( new Btn1Listener(this) );*/
    tstNetwrkBt = (Button) findViewById(R.id.buttons);
    tstNetwrkBt.setOnClickListener( new Test(this));

    }

      

  • 相关阅读:
    Java(14):面向对象、封装、继承、方法重写、多态、抽象类与接口、内部类
    Java(13):数组、Arrays类、冒泡排序
    Java(12):方法、重载、命令行传参、可变参数、方法调用
    Java(11):switch、dowhile、九九乘法表、打印质数、打印三角形
    Java(10):用户交互Scanner
    Java(9):包
    Java(8):运算符
    Java(7):变量和常量及其规范、作用域
    Mybatis 打印日志
    mysql 更新数据
  • 原文地址:https://www.cnblogs.com/hgs1314/p/6087411.html
Copyright © 2011-2022 走看看