Android检测手机或PAD是否连网
1. 引言
在进行Android手机或PAD的网络开发过程中,检测是否已经连接互连网是必不可少的一步,下面介绍其代码实现。
2. 功能实现
(1) 主布局(main.xml)实现:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
- android:orientation = "vertical"
- android:layout_width = "fill_parent"
- android:layout_height = "fill_parent"
- >
- <Button
- android:id = "@+id/checkNetWork"
- android:text = "检测网络"
- android:layout_width = "wrap_content"
- android:layout_height = "wrap_content"
- />
- </LinearLayout>
(2) 主Activity实现:
- package com.flora;
- import android.app.Activity;
- import android.content.Context;
- import android.net.ConnectivityManager;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
- public class NetWorkActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button checkNetWork = (Button) findViewById(R.id.checkNetWork);
- checkNetWork.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- if (checkNetWorkStatus()) {
- Toast.makeText(NetWorkActivity.this, "连接成功!", Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(NetWorkActivity.this, "连接失败!", Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
- private boolean checkNetWorkStatus() {
- boolean netSataus = false;
- ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- cwjManager.getActiveNetworkInfo();
- if (cwjManager.getActiveNetworkInfo() != null) {
- netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
- }
- return netSataus;
- }
- }
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20