在发送任何HTTP请求前最好检查下网络连接状态,这样可以避免异常。这个教程将会介绍怎样在你的应用中检测网络连接状态。

创建新的项目

1.在Eclipse IDE中创建一个新的项目并把填入必须的信息。  File->New->Android Project
2.创建新项目后的第一步是要在AndroidManifest.xml文件中添加必要的权限。
  • 为了访问网络我们需要 INTERNET 权限
  • 为了检查网络状态我们需要 ACCESS_NETWORK_STATE 权限

AndroidManifest.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml

version
="1.0"

encoding
="utf-8"?>
<manifest

xmlns:android
="http://schemas.android.com/apk/res/android"
    package="com.example.detectinternetconnection"
    android:versionCode="1"
    android:versionName="1.0"

>
  
    <uses-sdk

android:minSdkVersion
="8"

/>
  
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"

>
        <activity
            android:name=".AndroidDetectInternetConnectionActivity"
            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>
  
    <!--
Internet Permissions -->
    <uses-permission

android:name
="android.permission.INTERNET"

/>
  
    <!--
Network State Permissions -->
    <uses-permission

android:name
="android.permission.ACCESS_NETWORK_STATE"

/>
  
</manifest>
3.创建一个新的类,名为ConnectionDetector.java,并输入以下代码。
ConnectionDetector.java 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package

com.example.detectinternetconnection;
  
import

android.content.Context;
import

android.net.ConnectivityManager;
import

android.net.NetworkInfo;
  
public

class

ConnectionDetector {
  
    private

Context _context;
  
    public

ConnectionDetector(Context context){
        this._context
= context;
    }
  
    public

boolean

isConnectingToInternet(){
        ConnectivityManager
connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if

(connectivity != 
null)
          {
              NetworkInfo[]
info = connectivity.getAllNetworkInfo();
              if

(info != 
null)
                  for

(
int

i = 
0;
i < info.length; i++)
                      if

(info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return

true
;
                      }
  
          }
          return

false
;
    }
}

4.当你需要在你的应用中检查网络状态时调用isConnectingToInternet()函数,它会返回true或false。

?
1
2
3
ConnectionDetector
cd = 
new

ConnectionDetector(getApplicationContext());
  
Boolean
isInternetPresent = cd.isConnectingToInternet(); 
//
true or false
5.在这个教程中为了测试我仅仅简单的放置了一个按钮。只要按下这个按钮就会弹出一个 alert dialog 显示网络连接状态。

6.打开 res/layout 目录下的 main.xml 并创建一个按钮。
main.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml

version
="1.0"

encoding
="utf-8"?>
<RelativeLayout

xmlns:android
="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"

>
  
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Detect
Internet Status"

/>
  
    <Button

android:id
="@+id/btn_check"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check
Internet Status"
        android:layout_centerInParent="true"/>
  
</RelativeLayout>

7.最后打开你的 MainActivity 文件并粘贴下面的代码。在下面的代码中我用一个 alert dialog 来显示预期的状态信息。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package

com.example.detectinternetconnection;
  
import

android.app.Activity;
import

android.app.AlertDialog;
import

android.content.Context;
import

android.content.DialogInterface;
import

android.os.Bundle;
import

android.view.View;
import

android.widget.Button;
  
public

class

AndroidDetectInternetConnectionActivity 
extends

Activity {
  
    //
flag for Internet connection status
    Boolean
isInternetPresent = 
false;
  
    //
Connection detector class
    ConnectionDetector
cd;
  
    @Override
    public

void

onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        Button
btnStatus = (Button) findViewById(R.id.btn_check);
  
        //
creating connection detector class instance
        cd
new

ConnectionDetector(getApplicationContext());
  
        /**
         *
Check Internet status button click event
         *
*/
        btnStatus.setOnClickListener(new

View.OnClickListener() {
  
            @Override
            public

void

onClick(View v) {
  
                //
get Internet status
                isInternetPresent
= cd.isConnectingToInternet();
  
                //
check for Internet status
                if

(isInternetPresent) {
                    //
Internet Connection is Present
                    //
make HTTP requests
                    showAlertDialog(AndroidDetectInternetConnectionActivity.this"Internet
Connection"
,
                            "You
have internet connection"
true);
                else

{
                    //
Internet connection is not present
                    //
Ask user to connect to Internet
                    showAlertDialog(AndroidDetectInternetConnectionActivity.this"No
Internet Connection"
,
                            "You
don't have internet connection."
false);
                }
            }
  
        });
  
    }
  
    /**
     *
Function to display simple Alert Dialog
     *
@param context - application context
     *
@param title - alert dialog title
     *
@param message - alert message
     *
@param status - success/failure (used to set icon)
     *
*/
    public

void

showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog
alertDialog = 
new

AlertDialog.Builder(context).create();
  
        //
Setting Dialog Title
        alertDialog.setTitle(title);
  
        //
Setting Dialog Message
        alertDialog.setMessage(message);
  
        //
Setting alert dialog icon
        alertDialog.setIcon((status)
? R.drawable.success : R.drawable.fail);
  
        //
Setting OK Button
        alertDialog.setButton("OK"new

DialogInterface.OnClickListener() {
            public

void

onClick(DialogInterface dialog, 
int

which) {
            }
        });
  
        //
Showing Alert Message
        alertDialog.show();
    }
}

运行并测试下你的程序吧!你将会得到类似下面的结果。

怎样检查Android网络连接状态的更多相关文章

  1. Android 网络连接状态的监控

    有些应用需要连接网络,例如更新后台服务,刷新数据等,最通常的做法是定期联网,直接使用网上资源.缓存数据或执行一个下载任务来更新数据. 但是如果终端设备没有连接网络,或者网速较慢,就没必要执行这些任务. ...

  2. android 检查网络连接状态实现步骤

    获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="android.permission.AC ...

  3. Silverlight项目笔记6:Linq求差集、交集&检查网络连接状态&重载构造函数复用窗口

    1.使用Linq求差集.交集 使用场景: 需要从数据中心获得用户数据,并以此为标准,同步系统的用户信息,对系统中多余的用户进行删除操作,缺失的用户进行添加操作,对信息更新了的用户进行编辑操作更新. 所 ...

  4. Android 检测网络连接状态

    Android连接网络的时候,并不是每次都能连接到网络,因此在程序启动中需要对网络的状态进行判断,如果没有网络则提醒用户进行设置. 首先,要判断网络状态,需要有相应的权限,下面为权限代码(Androi ...

  5. Android编程获取网络连接状态(3G/Wifi)及调用网络配置界面

    随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityManager  类,用 ...

  6. Android编程 获取网络连接状态 及调用网络配置界面

    获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...

  7. Android编程获取网络连接状态及调用网络配置界面

    获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...

  8. 【Android进阶】判断网络连接状态并自动界面跳转

    用于判断软件打开时的网络连接状态,若无网络连接,提醒用户跳转到设置界面 /** * 设置在onStart()方法里面,可以在界面每次获得焦点的时候都进行检测 */ @Override protecte ...

  9. 用delphi检查网络连接状态3种方式

    用delphi检查网络连接状态3种方式 用delphi检查网络连接状态 检测计算机是否联网比较简单的做法可以通过一个 Win32 Internet(WinInet) 函数 InternetCheckC ...

随机推荐

  1. IO(下)

    7. 标准输入.输出流 7.1 标准输入流 源数据源是标准输入设备(键盘.鼠标.触摸屏)等输入设备.在java中用http://System.in 得到一个 InputStream 字节输入流. 需求 ...

  2. re正则表达式公式讲解6

    标识符 re.I (re.IGNORECASE) 忽略大小写 import re s = "Max@123uyt146" print(re.search("m" ...

  3. python绘图工具包 matplotlib 中文乱码问题

    环境: python2.7 windows 8.1 解决: 改配置文件,把字体改为支持中文的字体. 找到python安装目录下的 \Lib\site-packages\matplotlib\mpl-d ...

  4. SEO & HTML语义化

    SEO SEO的概念:搜索引擎优化,常见的搜索引擎有百度.谷歌等.优化的话,就是通过我们的处理,使得我们的网站在搜索引擎下有一个理想的结果. SEO的目的:当用户在搜索引擎上搜索关键词的时候,看到我们 ...

  5. TFS强制删除离职人员签出锁定项的方法(转)

      项目组一哥们走的时候以独占方式迁出了文件,现在其他人都无法修改,管理员似乎也无法将文件解除.经过摸索,找到了一种暴力的方法——直接改TFS数据库.虽然暴力,却能实实在在地解决这个问题. 步骤: 1 ...

  6. Hadoop 常用命令之 HDFS命令

    命令 说明 hadoop fs -mkdir 创建HDFS目录 hadoop fs -ls 列出HDFS目录 hadoop fs -copyFromLocal 使用-copyFromLocal 复制本 ...

  7. 微信小程序开发系列一:微信小程序的申请和开发环境的搭建

    我最近也刚刚开始微信小程序的开发,想把我自学的一些心得写出来分享给大家. 这是第一篇,从零开始学习微信小程序开发.主要是小程序的注册和开发环境的搭建. 首先我们要在下列网址申请一个属于自己的微信小程序 ...

  8. SQLite - SELECT查询

    SQLite - SELECT查询 SQLite SELECT语句用于获取数据从一个SQLite数据库表返回数据结果表的形式.也称为result-sets这些结果表. 语法 SQLite SELECT ...

  9. 在Eclipse中通过JDBC连接MySQL步骤,非常详细!

    通过JDBC连接MySQL基本步骤代码讲解步骤可能遇到的Bug基本步骤JDBC访问MySQL 1.加载JDBC驱动器—>哪个project需要,就添加到该project的jdbc文件夹下,我的j ...

  10. 什么是cookie(前段时间看到别人简历上把cookie和localStorage混淆了所以专门又去了解了下)

    在前端面试中,有一个必问的问题:请你谈谈cookie和localStorage有什么区别啊? localStorage是H5中的一种浏览器本地存储方式,而实际上,cookie本身并不是用来做服务器存储 ...