zoukankan      html  css  js  c++  java
  • Android检测网络是否可用

    public class Main extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        public void click(View view) {
            
            if(isConn()){
                Toast.makeText(this, "网络可用", 0).show();
            }else{
                Toast.makeText(this, "网络不可用", 0).show();
                setNetworkMethod();
            }
            
    
        }
    
        private boolean isConn() {
            boolean flag = false;
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo network = cm.getActiveNetworkInfo();
            if (network != null) {
                flag = network.isAvailable();
            }
            return flag;
        }
        
        private void setNetworkMethod(){
            
            AlertDialog.Builder builder = new Builder(this);
            builder.setTitle("网络设置提示");
            builder.setMessage("网络连接不可用,是否进行设置?");
            builder.setPositiveButton("设置", new DialogInterface.OnClickListener(){
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = null;
                    //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                    if(android.os.Build.VERSION.SDK_INT>10){
                        intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                    }else{
                        intent = new Intent();
                        intent.setClassName("com.android.settings","com.android.settings.WirelessSettings");
                    }
                    startActivity(intent);                
                }
                
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
            
            
            
        }
        
        
    
    }

    需要添加一个权限:android.permission.ACCESS_NETWORK_STATE
  • 相关阅读:
    清除cookie
    判断是否为中文
    正则表达式
    smarty基础语法
    smarty模板
    ajax
    php工作笔记1
    PHP中超全局变量$GLOBALS和global的区别
    SQL连表查询
    linux上安装git(客户端)及GitHub的配置
  • 原文地址:https://www.cnblogs.com/ahwu/p/3406386.html
Copyright © 2011-2022 走看看