zoukankan      html  css  js  c++  java
  • Android——检查网络是否已经链接

    新建一个项目testNet

    添加一个button

      layout.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.testnet.MainActivity" >
     
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
         <Button
            android:id="@+id/testNetwrkBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView1"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="31dp"
            android:text="@string/btn_testNet" />
    </RelativeLayout>

      

    新建一个外部类,实现接口OnClickListener

      

    Btn1Listener.java:

      

    package com.example.testnet;
    
    import android.app.Activity;
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    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 TextView tv1;
        private ConnectivityManager cm;
        public Btn1Listener(Context context) {
            this.context = context;
        }
    
        @Override
        public void onClick(View v) {
            //把上下文对象转型为Activity
            Activity c = ((Activity) context);
            //获取文本控件
            tv1 = (TextView) c.findViewById(R.id.textView1);
    //        tv1.setBackgroundColor(0);
            try{
                //获取网络。。。。
                cm = (ConnectivityManager) c.getSystemService(c.CONNECTIVITY_SERVICE);
                NetworkInfo info = cm.getActiveNetworkInfo();
                if(info == null){
                    //提示没有网络
                    tv1.setText(R.string.text_Net1);
                    tv1.setBackgroundResource(R.color.red);
                }else{
                    tv1.setText(R.string.text_Net0);
                    tv1.setBackgroundResource(R.color.green);
                    //不需要提示,继续执行相关的代码
                }
            }catch(RuntimeException e){
                //用户没授权的时候给出提示(由于不知道怎么提示用户授权,只能用Toast了,怪我小白)
                Toast.makeText(c, "没有权限,请授权", Toast.LENGTH_SHORT).show();
            }
        }
    
    }

    然后在Activity类给button绑定点击事件

      

    package com.example.testnet;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Button;
    
    
    public class MainActivity extends Activity {
        private Button btn1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btn1 = (Button) findViewById(R.id.testNetwrkBtn);
            btn1.setOnClickListener(new Btn1Listener(this));
        }
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

    注意:检查网络链接需要在AndroidManifest.xml中授予相关权限

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.testnet"
        android:versionCode="1"
        android:versionName="1.0" >
        <!-- 授予局域网权限 -->
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />
        <!-- 授予互联网权限 -->
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-sdk
            android:minSdkVersion="17"
            android:targetSdkVersion="20" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

    然后就可以运行了:

    网络已连接的运行结果:

      

    网络未连接的运行结果:

      

    最后是用户没有授权的结果:

    由于我的是模拟器,实在找不到怎么取消他的权限,所以我把AndroidManifest.xml的授权注释掉了→_→:

      

  • 相关阅读:
    ZJOI2017 Day3 滚粗记
    ZJOI2017 Day2
    bzoj4245 [ONTAK2015]OR-XOR (贪心)
    bzoj4631 踩气球 (树状数组+线段树)
    bzoj5219 [Lydsy2017省队十连测]最长路径 (DP)
    bzoj5216 [Lydsy2017省队十连测]公路建设 (线段树)
    bzoj2754 [SCOI2012]喵星球上的点名 (后缀数组+树状数组)
    bzoj2342 [Shoi2011]双倍回文 (manacher)
    bzoj4657 tower (最小割)
    bzoj2064 分裂 (状压dp)
  • 原文地址:https://www.cnblogs.com/liangshijie/p/6085818.html
Copyright © 2011-2022 走看看