android中NetWorkReceive以及擷取當前的網路連接狀態詳解

來源:互聯網
上載者:User

android中NetWorkReceive以及擷取當前的網路連接狀態詳解

我們現在APP是斷然很難離開網路存活下去,會有很多很頻繁的網路操作,請求資料,傳遞資料等等,所以,我們需要對網路狀態有多一點的瞭解。

首先,假如我們的APP在啟動並執行時候,假如這時候使用者掉線了,沒有網路了,我們就應該給使用者提示,然後使用者連上網路了,我們這時候應該也給使用者提示,這樣他就可以繼續玩我們的APP,我們應該怎麼做了,沒錯,就是通過Receiver來實現,因為斷網和連網系統都會發送廣播,然後,我們可以收到,通過廣播去判斷當前的網路是否可用,具體代碼如下:其中,接受廣播需要的action是android.net.conn.CONNECTIVITY_CHANGE和ta.android.net.conn.CONNECTIVITY_CHANGE,我們需要註冊該廣播接受者的時候添加過濾器,這樣他就可以收到了。

import com.iyueju.guanggong.util.NetWorkUtil;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;import android.widget.Toast;/** * 用於接受網路狀態的變化的receiver *  * @author Administrator * */public class NetWorkReceiver extends BroadcastReceiver{private static Boolean networkAvailable = false;// 預設網路狀態private static com.iyueju.guanggong.util.NetWorkUtil.netType type;private final static String ANDROID_NET_CHANGE_ACTION = android.net.conn.CONNECTIVITY_CHANGE;public final static String TA_ANDROID_NET_CHANGE_ACTION = ta.android.net.conn.CONNECTIVITY_CHANGE;private static NetWorkReceiver receiver;private NetWorkReceiver(){super();}public static NetWorkReceiver getNetWorkReceiver(){// TODO Auto-generated constructor stubif (receiver == null){synchronized (NetWorkReceiver.class){if (receiver == null){receiver = new NetWorkReceiver();}}}return receiver;}@Overridepublic void onReceive(Context context, Intent intent){// TODO Auto-generated method stureceiver = NetWorkReceiver.this;if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION)    || intent.getAction().equalsIgnoreCase(TA_ANDROID_NET_CHANGE_ACTION)){Log.i(Main, 有收到網路連接的相關訊息);if (!NetWorkUtil.isNetworkAvailable(context) && networkAvailable == true){Log.i(Main, 斷開了網路);networkAvailable = false;Toast.makeText(context, 網路不可用, 1).show();} else if (NetWorkUtil.isNetworkAvailable(context) && networkAvailable == false){Log.i(Main, 網路連接成功);networkAvailable = true;type = NetWorkUtil.getAPNType(context);Toast.makeText(context, 網路連接成功, 1).show();}}}/** * 註冊網路監聽 *  * @param context */public static void registerNetworkStateReceiver(Context context){Intent intent = new Intent();intent.setAction(TA_ANDROID_NET_CHANGE_ACTION);context.sendBroadcast(intent);}/** * 顯示當前網路狀態 *  * @param context */public static void checkNetWorkState(Context context){Intent intent = new Intent();intent.setAction(TA_ANDROID_NET_CHANGE_ACTION);context.sendBroadcast(intent);}/** * 登出網路監聽 *  * @param context */public static void unRegisterNetworkStateReceiver(Context context){if (receiver != null){try{context.getApplicationContext().unregisterReceiver(receiver);} catch (Exception e){e.printStackTrace();}}}public static Boolean isNetWorkAvailable(){return networkAvailable;}public static com.iyueju.guanggong.util.NetWorkUtil.netType getNetWorkType(){return type;}}

註冊監聽:

/** * 註冊監聽 */private void registerMessageReceiver(){// TODO Auto-generated method stubNetWorkReceiver receiver = NetWorkReceiver.getNetWorkReceiver();IntentFilter filter = new IntentFilter();filter.addAction(android.net.conn.CONNECTIVITY_CHANGE);filter.addAction(android.gzcpc.conn.CONNECTIVITY_CHANGE);registerReceiver(receiver, filter);}


然後,需要在不適用APP的時候登出

則是:

unregisterReceiver(NetWorkReceiver.getNetWorkReceiver());


然後,假如是我們的APP中,我們通過一些view的點擊或者其他的事件觸發一些網路操作,為了避免一些錯誤,我們需要先去判斷當前網路是否可用,當前串連的網路不是是wifi(為使用者考慮)以及當前是否有網路連接,還有當前的網速是多大,是否適合我們的操作等等。

下面是具體的代碼實現:

import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import com.iyueju.guanggong.constant.APPConstant;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Handler;import android.os.Message;import android.util.Log;/** * 網路工具類 *  * @author Administrator * */public class NetWorkUtil{// Private fieldsprivate static final String TAG = NetWorkUtil.class.getSimpleName();private static final int EXPECTED_SIZE_IN_BYTES = 1048576;// 1MB 1024*1024private static final double BYTE_TO_KILOBIT = 0.0078125;private static final double KILOBIT_TO_MEGABIT = 0.0009765625;private static Handler mHandler;public static int timer;// 網路狀態,串連wifi,cmnet是直連互連網的,cmwap是需要代理,noneNet是不需連線的// 一速度來說:wifi > cmnet >cmwap > noneNetpublic static enum netType{wifi, CMNET, CMWAP, noneNet}/** * 網路是否可用 *  * @param context * @return */public static boolean isNetworkAvailable(Context context){// 擷取網路managerConnectivityManager mgr = (ConnectivityManager) context    .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo[] info = mgr.getAllNetworkInfo();// 遍曆所有可以串連的網路if (info != null){for (int i = 0; i < info.length; i++){if (info[i].getState() == NetworkInfo.State.CONNECTED){return true;}}}return false;}/** * 判斷是否有網路連接 *  * @param context * @return */public static boolean isNetworkConnected(Context context){if (context != null){ConnectivityManager mConnectivityManager = (ConnectivityManager) context    .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();if (mNetworkInfo != null){return mNetworkInfo.isAvailable();}}return false;}/** * 判斷WIFI網路是否可用 *  * @param context * @return */public static boolean isWifiConnected(Context context){if (context != null){ConnectivityManager mConnectivityManager = (ConnectivityManager) context    .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mWiFiNetworkInfo = mConnectivityManager    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);if (mWiFiNetworkInfo != null){return mWiFiNetworkInfo.isAvailable();}}return false;}/** * 判斷MOBILE網路是否可用 *  * @param context * @return */public static boolean isMobileConnected(Context context){if (context != null){ConnectivityManager mConnectivityManager = (ConnectivityManager) context    .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mMobileNetworkInfo = mConnectivityManager    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);if (mMobileNetworkInfo != null){return mMobileNetworkInfo.isAvailable();}}return false;}/** * 擷取當前網路連接的類型資訊 *  * @param context * @return */public static int getConnectedType(Context context){if (context != null){ConnectivityManager mConnectivityManager = (ConnectivityManager) context    .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();if (mNetworkInfo != null && mNetworkInfo.isAvailable()){return mNetworkInfo.getType();}}return -1;}/** *  * @author 白貓 *  *         擷取當前的網路狀態 -1:沒有網路 1:WIFI網路2:wap 網路3:net網路 *  * @param context *  * @return */public static netType getAPNType(Context context){ConnectivityManager connMgr = (ConnectivityManager) context    .getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();if (networkInfo == null){return netType.noneNet;}int nType = networkInfo.getType();if (nType == ConnectivityManager.TYPE_MOBILE){if (networkInfo.getExtraInfo().toLowerCase().equals(cmnet)){return netType.CMNET;}else{return netType.CMWAP;}} else if (nType == ConnectivityManager.TYPE_WIFI){return netType.wifi;}return netType.noneNet;}/** * 測試網速 *  * @param handler */public static void textSpeed(Handler handler){mHandler = handler;new Thread(mWorker).start();}/** * Our Slave worker that does actually all the work */private static final Runnable mWorker = new Runnable(){@Overridepublic void run(){InputStream stream = null;try{int bytesIn = 0;String downloadFileUrl = http://120.24.237.77/test;long startCon = System.currentTimeMillis();URL url = new URL(downloadFileUrl);URLConnection con = url.openConnection();con.setUseCaches(false);long connectionLatency = System.currentTimeMillis() - startCon;stream = con.getInputStream();Message msgUpdateConnection = Message.obtain(mHandler,    APPConstant.MSG_UPDATE_CONNECTION_TIME);msgUpdateConnection.arg1 = (int) connectionLatency;mHandler.sendMessage(msgUpdateConnection);long start = System.currentTimeMillis();int currentByte = 0;long updateStart = System.currentTimeMillis();long updateDelta = 0;int bytesInThreshold = 0;while ((currentByte = stream.read()) != -1){bytesIn++;bytesInThreshold++;if (updateDelta >= APPConstant.UPDATE_THRESHOLD){int progress = (int) ((bytesIn / (double) EXPECTED_SIZE_IN_BYTES) * 100);Message msg = Message.obtain(mHandler, APPConstant.MSG_UPDATE_STATUS,    calculate(updateDelta, bytesInThreshold));msg.arg1 = progress;msg.arg2 = bytesIn;mHandler.sendMessage(msg);// ResetupdateStart = System.currentTimeMillis();bytesInThreshold = 0;}updateDelta = System.currentTimeMillis() - updateStart;}long downloadTime = (System.currentTimeMillis() - start);// Prevent AritchmeticExceptionif (downloadTime == 0){downloadTime = 1;}Message msg = Message.obtain(mHandler, APPConstant.MSG_COMPLETE_STATUS,    calculate(downloadTime, bytesIn));msg.arg1 = bytesIn;mHandler.sendMessage(msg);} catch (MalformedURLException e){Log.e(TAG, e.getMessage());} catch (IOException e){Log.e(TAG, e.getMessage());} finally{try{if (stream != null){stream.close();}} catch (IOException e){// Suppressed}}}};/** *  * 1 byte = 0.0078125 kilobits 1 kilobits = 0.0009765625 megabit *  * @param downloadTime *          in miliseconds * @param bytesIn *          number of bytes downloaded * @return SpeedInfo containing current speed */private static SpeedInfo calculate(final long downloadTime, final long bytesIn){SpeedInfo info = new SpeedInfo();// from mil to seclong bytespersecond = (bytesIn / downloadTime) * 1000;double kilobits = bytespersecond * BYTE_TO_KILOBIT;double megabits = kilobits * KILOBIT_TO_MEGABIT;info.downspeed = bytespersecond;info.kilobits = kilobits;info.megabits = megabits;return info;}/** * Transfer Object *  * @author devil * */public static class SpeedInfo{public double kilobits = 0;public double megabits = 0;public double downspeed = 0;}}


其中,涉及到了四個其他常量是:

public static final int MSG_UPDATE_STATUS = 0;public static final int MSG_UPDATE_CONNECTION_TIME = 1;public static final int MSG_COMPLETE_STATUS = 2;public static final int UPDATE_THRESHOLD = 300;


注意:使用的時候需要加入一些許可權,

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.