学习Android SDK Samples之旅-connectivity篇

【学习目的】android有一些很有意思的API,以及示范性的代码写法就藏在 androidSdk目录/samples之下,但是我们往往都忽视了。

【分享目的】看androidSdk的Samples还是挺费时间的,而且因为英文不好啊,或者缺少讲解指引呀,往往看了半天,费了很大劲也不得精髓,所以我想把一些包里的Demo代码一一看过去,分享比较实用的代码,帮助大家更好地学习,同时也算是自己的一种积累吧。

【本次主题】.../sdk/samples/android-23/connectivity


【1】/BasicNetworking

这个项目有2个有趣的地方:

⑴ 网络判断方法:判断当前设备是否联网,以及判断联网是wifi还是移动流量

/**
 * Check whether the device is connected, and if so, whether the connection
 * is wifi or mobile (it could be something else).
 */
private void checkNetworkConnection() {

    ConnectivityManager connMgr =
      (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
    if (activeInfo != null && activeInfo.isConnected()) {
        wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
        mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        if(wifiConnected) {
          Log.i(TAG, getString(R.string.wifi_connection));
        } else if (mobileConnected){
          Log.i(TAG, getString(R.string.mobile_connection));
        }
    } else {
        Log.i(TAG, getString(R.string.no_wifi_or_mobile));
    }

}

(2) 链条chain:
public interface LogNode {

    /**
     * Instructs first LogNode in the list to print the log data provided.
     * @param priority Log level of the data being logged.  Verbose, Error, etc.
     * @param tag Tag for for the log data.  Can be used to organize log statements.
     * @param msg The actual message to be logged. The actual message to be logged.
     * @param tr If an exception was thrown, this can be sent along for the logging facilities
     *           to extract and print useful information.
     */
    public void println(int priority, String tag, String msg, Throwable tr);

}
图解
学习Android SDK Samples之旅-connectivity篇_第1张图片
其中LogWrapper中运用了android.util.Log,真正的系统Log类,其他每个类在实现LogNode接口中的println的方法时,会先运行自己的代码,最后一句写上
if  (mNext != null) {
mNext.print(priority, tag, msg, tr);
}

这样这些类就像链条(chain)一样一环环连接下去了。

换句话说,调用Log的println方法,那么就会带上LoggerWrapper的println,MessageOnlyLogFilter的println,以及LogView的println一起执行。

(后面的我一篇一篇补)


你可能感兴趣的:(android,sdk,samples,移动,wi-fi)