怎样检查Android网络连接状态
来源:互联网 发布:linux安装软件包 编辑:程序博客网 时间:2024/04/28 06:47
在发送任何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();
}
}
运行并测试下你的程序吧!你将会得到类似下面的结果。
0 0
- 怎样检查Android网络连接状态
- Android:检查网络连接状态
- Android 检查网络连接状态
- 检查Android网络连接状态
- Android检查网络连接状态
- 如何检查Android网络连接状态
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- android 检查网络连接状态实现步骤
- 如何检查Android网络连接状态
- android 检查网络连接状态实现步骤
- 检查Android网络连接状态(转载)
- 教育杂谈
- 嘻嘻哈的
- 构造函数有参数,无参数,重载的运用
- document.body.scrollLeft的兼容方法
- java soap webservice(含有SoapHeader)
- 怎样检查Android网络连接状态
- 智能遥控瓦力 – 瓦力模型到手啦
- Spring的事务管理基础情况(六)
- ssh免密码登录
- find your present (2)(按位异或)
- fghfghfg
- Android ORMLite 框架的入门用法
- NSParameterAssert一点纪录
- Wifi小车之 – 最终版