android ConnectivityManager 檢查是否有網絡


 

  一.   ConnectivityManager

     概要

     ConnectivityManager是網絡連接相關的管理器,它主要用於查詢網絡狀態並在網絡發生改變時發出狀態變化通知。這個類主要負責的下列四個方面:

     1.  監控網絡狀態(包括WiFi, GPRS, UMTS等)。

     2.  當網絡連接改變時發送廣播Intent。

     3.  當一種網絡斷開時,試圖連接到另一種網絡進行故障處理。

     4.  提供一系列接口讓應用程序查詢可獲得的網絡的粗粒度和細粒度狀態。 

 比較重要的幾個類常量

int

TYPE_BLUETOOTH

The Bluetooth data connection. 藍牙數據連接

int

TYPE_ETHERNET

The Ethernet data connection. 以太網數據連接

int

TYPE_MOBILE

The Mobile data connection. 移動數據鏈接

int

TYPE_WIFI

The WIFI data connection. wifi鏈接

 

 


 

 

 

 

String

CONNECTIVITY_ACTION

網絡連接發生改變

int

DEFAULT_NETWORK_PREFERENCE

默認網絡連接偏好,建議在config.xml中進行配置.並通過調用 getNetworkPreference() 獲取應用的當前設置值。

String

EXTRA_EXTRA_INFO

The lookup key for a string that provides optionally supplied extra information about the network state.查詢關鍵字,提供關於網絡狀態的信息

String

EXTRA_NETWORK_INFO

建議使用getActiveNetworkInfo() or getAllNetworkInfo()獲取網絡連接信息

String

EXTRA_NETWORK_TYPE

觸發 CONNECTIVITY_ACTION廣播的網絡類型

 

 

 

 

 

 


      

 

 

比較重要的方法
   

 

NetworkInfo

getActiveNetworkInfo() 獲取當前連接可用的網絡

NetworkInfo[]

getAllNetworkInfo() 獲取設備支持的所有網絡類型的鏈接狀態信息。

NetworkInfo

getNetworkInfo(int networkType)  獲取特定網絡類型的鏈接狀態信息

int

getNetworkPreference()  獲取當前偏好的網絡類型。

boolean

isActiveNetworkMetered() 

Returns if the currently active data network is metered.

static boolean

isNetworkTypeValid(int networkType)   判斷給定的數值是否表示一種網絡

boolean

requestRouteToHost(int networkType, int hostAddress)

Ensure that a network route exists to deliver traffic to the specified host via the specified network interface.

void

setNetworkPreference(int preference)

Specifies the preferred network type.

int

startUsingNetworkFeature(int networkType, String feature)

Tells the underlying networking system that the caller wants to begin using the named feature.

int

stopUsingNetworkFeature(int networkType, String feature)

Tells the underlying networking system that the caller is finished using the named feature.

 

     

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

最后奉上一點點干貨:

創建一個項目   我的項目名(testnet-note)

 

com.example.testnet_note下創建一個Btu1Listener.java   完成 onClick事件

/testNet-note/src/com/example/testnet_note/Btu1Listener.java

package com.example.testnet_note;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

/**
 * ConnectivityManager ConnectivityManager主要管理和網絡連接相關的操作
 * 相關的TelephonyManager則管理和手機、運營商等的相關信息;WifiManager則管理和wifi相關的信息。 想訪問網絡狀態,首先得添加權限
 * NetworkInfo類包含了對wifi和mobile兩種網絡模式連接的詳細描述,
 * 通過其getState()方法獲取的State對象則代表着連接成功與否等狀態。
 * 
 */
public class Btu1Listener implements OnClickListener {

    private Context conntxt; // 上下文
    private TextView tv1; // 文本控件
    private ConnectivityManager cm; // 主要管理和網絡連接相關的操作
    private NetworkInfo netInfo;
    private String netStatus;
    private int color1;

    public Btu1Listener(Context conntxt) {
        this.conntxt = conntxt;
    }

    public void onClick(View v) {
        try {
            Activity c = (Activity) conntxt;
            tv1 = (TextView) c.findViewById(R.id.textView1);
            cm = (ConnectivityManager) c
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            // 獲取代表聯網狀態的NetWorkInfo對象
            netInfo = cm.getActiveNetworkInfo(); // getActiveNetworkInfo()

            if (netInfo == null) { // 提示沒有網絡
                netStatus = c.getResources().getString(R.string.netStatus0); // 提示文字
                color1 = c.getResources().getColor(R.color.red); // 背景顏色
            } else { // 網絡已連接
            // netStatus = c.getResources().getString(R.string.netStatus1);
            // color1 = c.getResources().getColor(R.color.green);
                // 獲得當前連接的網絡類型。
                // TYPE_MOBILE GPRS網絡
                if (State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()) {
                    netStatus = c.getResources().getString(R.string.netStatus2);
                    color1 = c.getResources().getColor(R.color.rosybrown);
                }
                // TYPE_WIFI WIFI網絡
                if (State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()) {
                    netStatus = c.getResources().getString(R.string.netStatus3);
                    color1 = c.getResources().getColor(R.color.lavender);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            tv1.setText(netStatus);
            tv1.setBackgroundColor(color1);
        }

    }

}

 

/testNet-note/res/layout/activity_main.xml 配制

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testnet_note.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:height="40dp"
        android:maxHeight="90dp"
        android:text="@string/hello_world"
        android:textSize="29sp" />

    <Button
        android:id="@+id/tstNetwrkBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="@string/btnShow" />

</RelativeLayout>

 

/testNet-note/res/values/styles.xml 配制

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">testNet-note</string>
    <string name="hello_world">網絡測試</string>
    <string name="btnShow">網絡測試</string>
    
    
    <string name="netStatus0">網絡不可用</string>
    <string name="netStatus1">當前的網絡連接可用</string>
    <string name="netStatus2">GPRS網絡已連接</string>
    <string name="netStatus3">WIFI網絡已連接</string>
    
    
    <string name="action_settings">Settings</string>

</resources>

/testNet-note/res/values/colors.xml 配制

<?xml version="1.0" encoding="utf-8"?>
<resources>


 <!-- 淡紫色 -->
    <color name="orchid">#DA70D6</color>
 <!-- 褐玫瑰紅 -->
    <color name="rosybrown">#BC8F8F</color>
 <!-- 紅色 -->
    <color name="red">#FF0000</color>
 <!-- 綠色 -->
    <color name="green">#008000</color>
 

</resources>

 

現在代碼寫完了   運行有錯誤   是權限問題

 

 加兩個權限就好了

 

 效果圖:

WiFi ╭(╯^╰)╮

開了   數據   2G/(ㄒoㄒ)/~~

 

感覺有bug    WiFi  數據   都關了  它才是   網絡不可用

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM