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));

    }

      

  • 相关阅读:
    最新国家标准下载(2020-7-31)
    SL/T 264-2020 水利水电工程岩石试验规程
    SH/T 3082-2019 石油化工仪表供电设计规范
    GB/T 4780-2020 汽车车身术语
    Java——冒泡排序
    JSP处理XML数据
    JSP标准标签库(JSTL)
    千锤百炼软工第十九天
    千锤百炼软工第十八天
    千锤百炼软工第十七天
  • 原文地址:https://www.cnblogs.com/hgs1314/p/6087411.html
Copyright © 2011-2022 走看看