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

    }

      

  • 相关阅读:
    implementaion bottle session with beaker
    [梦]20050802
    网站更新部署20100912
    Cherokee不值得推荐,你还是可以看一看
    最简单方法远程调试Python多进程子程序
    nginx相关的问题
    本地配置host解析的问题
    base target问题,
    在asp.net中自动合并小图片并使用css sprite显示出来
    html编辑器
  • 原文地址:https://www.cnblogs.com/hgs1314/p/6087411.html
Copyright © 2011-2022 走看看