实训笔记(二) 判断网络状态并触发响应事件

点击下载按钮是检查网络状态并根据网络状态做出相应动作:若无网络弹出对话框("去设置"和"取消")判断用户选择的操作执行相应的函数。

 1 //判断网络状态
 2     private boolean getNetWorkStatus() { 
 3 
 4         boolean netSataus = false; 
 5         ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
 6 
 7         cwjManager.getActiveNetworkInfo(); 
 8 
 9         if (cwjManager.getActiveNetworkInfo() != null) { 
10         netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
11         } 
12         return netSataus;
13     }
14 
15     public void btn_download(View view) {
16 //        Init_prefrences(view);
17 //        SharedPreferences preferences = getSharedPreferences("setting_pre",
18 //                MODE_PRIVATE);
19 //        String on_off = preferences.getString("download_only_wifi", "");
20 //        dtextview.setText(on_off);
21         if ( !getNetWorkStatus()) {
22 
23             Dialog alertDialog=new AlertDialog.Builder(this).setTitle("提示")
24                     .setMessage("无网络访问,是否去设置网络?")
25                     .setPositiveButton("确定",new DialogInterface.OnClickListener() {
26                         
27                         @Override
28                         public void onClick(DialogInterface arg0, int arg1) {
29                             // TODO Auto-generated method stub
30                             
31                         }
32                     })
33                     .setNegativeButton("去设置",new OnClickListener() {
34                         
35                         @Override
36                         public void onClick(DialogInterface arg0, int arg1) {
37                             // TODO Auto-generated method stub
38                             gosetting();
39                         }
40                     }).create();
41             
42             alertDialog.show();
43 
44         } else {
45             Toast errortoast = Toast.makeText(Creat.this, "异常出错",
46                     Toast.LENGTH_SHORT);
47             errortoast.show();
48         }
49 
50     }
51 
52     public void gosetting() {
53         Intent intent = new Intent("/");
54         ComponentName cm = new ComponentName("com.android.settings",
55                 "com.android.settings.Settings");
56         intent.setComponent(cm);
57         intent.setAction("android.intent.action.View");
58         this.startActivityForResult(intent, 0);
59     }


PS:添加权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" ></uses-permission>

转载于:https://www.cnblogs.com/fiveyearsago/p/3490817.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值