Android也架构之二:单例模式访问网络

oschina中没有代码插入,看带有代码的文章挺费劲的,若是你和我同样java

请移步:http://blog.csdn.net/michael_yy/article/details/7883621  或者个人我的网站 http://www.devchina.comandroid

首先咱们来看下单例模式的定义:安全

定义:在整个应用中,保证一个类只有一个实例,它提供了一个能够访问到它本身的全局访问点(静态方法)。网络

单例模式中有区分了懒汉式和饿汉式,懒汉式主要是用时间来换空间,饿汉式则是用空间来换时间。饿汉式是线程安全的,懒汉式是非线程安全的,若是要实现懒汉式的非线程安全,则能够再访问点添加synchronized关键字声明便可。在其余的一些项目中还使用了双重检测枷锁机制。架构

如今咱们来看下代码,我会提供代码下载供你们参考。app

AndroidManifest.xml文件ide

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"优化

    package="com.yangfuhai.singleton"网站

    android:versionCode="1"

    android:versionName="1.0" >


    <uses-sdk android:minSdkVersion="8" />


    <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name" >

        <activity

            android:name=".SingletonActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>


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

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

</manifest>


注意添加:

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

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


用于访问网络

activity代码 SingletonActivity

package com.yangfuhai.singleton;


import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;


/**

 * @title 单例模式

 * @description 单例模式

 * @company 探索者网络工做室(www.tsz.net)

 * @author michael Young (www.YangFuhai.com)

 * @version 1.0

 * @created 2012-8-19

 */

public class SingletonActivity extends Activity {

TextView mTv;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        mTv = (TextView) findViewById(R.id.textView);

        

        mTv.setText("正在加载www.devchina.com数据。。。");

        new Thread(new Runnable() {

@Override

public void run() {

final String strContext = HttpUtils.get().getUrlContext("http://www.devchina.com");

runOnUiThread(new Runnable() {

@Override

public void run() {

if(strContext!=null)

mTv.setText(strContext);

else

mTv.setText("加载失败。。。");

}

});

}

}).start();

        

    }

    

    

}



http访问网络代码HttpUtils,用单例模式实现

package com.yangfuhai.singleton;


import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.Reader;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.URL;


import android.util.Log;


/**

 * @title Http请求工具类

 * @description 请求http数据,单例模式

 * @company 探索者网络工做室(www.tsz.net)

 * @author michael Young (www.YangFuhai.com)

 * @version 1.0

 * @created 2012-8-19

 */

public class HttpUtils {

private static final String DEBUG_TAG = "HttpUtils";

private HttpUtils() {} //单例模式中,封闭建立实例接口

private static HttpUtils httpUtils = null; 

//提供了一个能够访问到它本身的全局访问点

public static HttpUtils get(){

if(httpUtils == null)

httpUtils = new HttpUtils();

return httpUtils;

}

/**

* 获取某个url的内容

* @param strUrl

* @return

*/

public String getUrlContext(String strUrl){

InputStream is = null;

   int len = 500;

       

   try {

       URL url = new URL(strUrl);

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

       conn.setReadTimeout(10000 /* milliseconds */);

       conn.setConnectTimeout(15000 /* milliseconds */);

       conn.setRequestMethod("GET");

       conn.setDoInput(true);

       conn.connect();

       int response = conn.getResponseCode();

       Log.d(DEBUG_TAG, "The response is: " + response);

       is = conn.getInputStream();

       

       //这里指获取了500(len=500)字节,若是想

       //整个网页所有获取能够用conn.getContentLength()来代替len

       String contentAsString = readInputStream(is, len);

       return contentAsString;

      

   } catch (Exception e) {

    e.printStackTrace();

   } finally {

       if (is != null) {

           try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

       } 

   }

   return null;

}

/**

* 读取 InputStream 内容

* @param stream

* @param len

* @return

* @throws IOException

* @throws UnsupportedEncodingException

*/

public String readInputStream(InputStream stream, int len) throws IOException, UnsupportedEncodingException {

   Reader reader = null;

   reader = new InputStreamReader(stream, "UTF-8");        

   char[] buffer = new char[len];

   reader.read(buffer);

   return new String(buffer);

}


}

源码下载地址:

http://download.csdn.net/detail/michael_yy/4511109

你们多多指教,转载请注明来之 www.devchina.com  或者 csdn, 谢谢。

谢谢你们关注,我继续在博客中讲解了经典的23中模式中在android实际项目中灵活运用,下一篇 《Android也架构之三:简单工厂模式优化网络请求》敬请关注。

相关文章
相关标签/搜索