Android 的網路連結狀態

來源:互聯網
上載者:User

標籤:

Android手機對於系統狀態的改變 ,如:信的接收,電話的接收,電池電量過低,網路狀態改變都會發一個廣播 。有了廣播機制,我們只需要建立一個廣播接受者來處理這個廣播,就可以實現在不同狀態下做出不同的操作、

本篇主要記錄一下對於網路狀態改變的監聽。首先定義一個類繼承NetworkChangeReceiver,重寫onReceive()就行了。然後在OnReceive()這個方法進行相應廣播的處理。

public class NetWorkReceiver extends BroadcastReceiver {
  public void onReceive(Context context, Intent intent) { State wifiState = null; State mobileState = null; ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) .getState(); if (mobileState != null && State.CONNECTED == mobileState) { // 行動電話通訊串連成功 if (cm.getActiveNetworkInfo().getExtraInfo().toLowerCase() .equals("cmnet")) { //cmnet連結 }else{ // cmwap連結,添加中國移動代理

                HttpHost proxy = new HttpHost("10.0.0.172", 80); 

                conn = (HttpURLConnection) url.openConnection(proxy);

                 }        } else if (State.CONNECTED != wifiState                && State.CONNECTED != mobileState) {            // 手機沒有任何的網路        } else if (wifiState != null && State.CONNECTED == wifiState) {            // 無線網路串連成功        }    }}

然後,我們需要在應用中註冊這個廣播,註冊廣播的方式有兩種,①在androidmanifest.xml中註冊

<receiver            android:name="com.test.NetworkBroadcast"            android:label="NetworkConnection" >            <intent-filter>                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />            </intent-filter></receiver>

②在java代碼中註冊,在Activity的OnCreate()方法中註冊,在onDestory()方法中卸載

private BroadcastReceiver networkBroadcast=new BroadcastReceiver(); IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); // 設定優先權filter.setPriority(Integer.MAX_VALUE);this.registerReceiver(networkBroadcast, filter);

卸載:

if(networkBroadcast != null){    this.unregisterReceiver(networkBroadcast);    networkBroadcast=null;}

③添加許可權

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

如果要程式隱藏在背景話,建議開個service,將BroadcastReceiver註冊在service。比如像電話攔截,IP撥號,檢測SD卡狀態,開機狀態等。

Android 的網路連結狀態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.