Handler+Thread+Message模式 Android线程网络

package com.example.httpdownloader;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;

import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity {
	
	private Context mContext;
	
	private Button downButton;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	         super.onCreate(savedInstanceState);
	         setContentView(R.layout.activity_main);
	         
	         
	         mContext=this.getApplicationContext();
	         downButton=(Button)findViewById(R.id.button1);
	         
	         if(checkNetworkIsActive(mContext))
	         {
	        	 Log.v("httpdownloader", "NetworkIsAvailabel");
	         }
	         else {
	        	 Log.v("httpdownloader", "Network Is Not Availabel");
			}
	         
	         /*检查游戏版本*/
	         Log.v("current version", "current version=  "+getCurrentVersionCode());
	         
	         downButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					
					/*新建线程来处理网络访问*/
					Thread thread=new Thread(){
						@Override
						public void run(){

							try {
								HttpDownloader httpdownloader=new HttpDownloader();
								String txtcontentString= httpdownloader.downLoadText("http://www.thisisgame.com.cn/sample-page/");
								Log.v("downloader", txtcontentString);
								
								int downback=httpdownloader.downloadFile("http://www.thisisgame.com.cn/darkelf_guard.zip", "", "darkelf_guard.zip");
								Log.v("downloadback", "downback = " + downback);
							} catch (Exception  e) {
								// TODO: handle exception
								Log.v("httpdownloader",e.getMessage());
							}
							
							/*在线程run的时候发消息通知主线程更新界面等*/
							Message message=handler.obtainMessage();
							
							/*这里是传递参数*/
							message.arg1=1212;
							//message.obj=;
							handler.sendMessage(message);
							
						}
					};
					thread.start();
					thread=null;	
				}
			});
	}
	
	
	final Handler handler=new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			/*在这里就可以对主线程进行更新*/
			Log.v("httpdownloader", "handleMessage param"+ msg.arg1);
		}
	};
	
	
	/*检查网络是否可用*/
	public static boolean checkNetworkIsActive(final Context context)
	{
		boolean mIsNetworkAvailabel=false;
		ConnectivityManager cManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info=cManager.getActiveNetworkInfo();
		if(info!=null)
		{
			mIsNetworkAvailabel=info.isAvailable();
		}
		return mIsNetworkAvailabel;
		
	}
	
	/*获取当前游戏版本*/
	public  int getCurrentVersionCode()
	{
		PackageManager manager=mContext.getPackageManager();
		try {
			PackageInfo info=manager.getPackageInfo(mContext.getPackageName(), 0);
			int oldVersion=info.versionCode;
			return oldVersion;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}

	}
	
}

以上MainActivity


FileUtil.java

package com.example.httpdownloader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtil {
	private String SDCARDPATH;
	public String getSDPath(){
		return SDCARDPATH;
	}
	
	public void setSDPath(String path)
	{
		SDCARDPATH=path;
	}
	
	public FileUtil()
	{
		SDCARDPATH=Environment.getExternalStorageDirectory()+"/";
	}
	
	/*在SD卡下面创建文件*/
	public File createSDFile(String filename) throws IOException
	{
		File file=new File(SDCARDPATH+filename);
		file.createNewFile();
		return file;
	}
	
	/*在SD卡下面创建目录*/
	public File createSDDir(String dirname)
	{
		File dir=new File(SDCARDPATH+dirname);
		dir.mkdir();
		return dir;
	}
	
	/*判断文件是不是存在*/
	public boolean isFileExist(String filename)
	{
		File file=new File(SDCARDPATH+filename);
		return file.exists();
	}
	
	/*将InputStream写入SD卡中,InputStream从HttpURLConnection.getInputStream()返回*/
	public File inputSD(String path,String fileName,InputStream inputstream)
    {
        File file=null;
        FileOutputStream outputstream=null;
        try {
            
            /*先创建目录*/
            createSDDir(path);
            
            /*创建文件*/
            file=createSDFile(path+fileName);
            
            /*从文件中获取到文件输出流*/
            outputstream=new FileOutputStream(file);
            
            /*4K  每次写入*/
            byte[] buffer=new byte[8*1024];
            
            /*从文件输入流中每次读取4kb到文件输出流,即每次写4kb到文件*/
            int size;
            while((size=inputstream.read(buffer,0,8*1024))!=-1)
            {
                outputstream.write(buffer,0,size);
            }
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            try{
                if(outputstream!=null)
                {
                    outputstream.flush();
                    outputstream.close();
                }
            }catch (IOException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        return file;
    }

}

HttpDownloader.java

package com.example.httpdownloader;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.R.integer;

public class HttpDownloader {
	private URL url=null;
	BufferedReader br=null;

	/*下载文本文件*/
	public String  downLoadText(String strurl) 
	{
		StringBuffer sb=new StringBuffer();
		String lineString=null;
		BufferedReader brBufferedReader=null;
		try {
			url=new URL(strurl);
			HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
			
			/* getInputStream()获取到字节流  封装成InputStreamReader,编程字符流  再封装成BufferedReader,就可以一行一行读取了 */
			br=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			while((lineString=br.readLine())!=null)
			{
				sb.append(lineString);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally
		{
			try {
				br.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	
	/*下载文件到SDCard*/
	/* 文件下载成功返回1 下载失败返回-1   文件已经存在返回0 */
	public int downloadFile(String strurl,String path,String fileName)
	{
		InputStream inputstream=null;
		FileUtil fileutils=new FileUtil();
		if(fileutils.isFileExist(path+fileName))
		{
			/* 如果文件已经存在返回0 */
			return 0;   
		}
		else
		{
			try {
				url=new URL(strurl);
				HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
				inputstream=urlConnection.getInputStream();
				File file=fileutils.inputSD(path, fileName, inputstream);
				
				/*文件下载失败返回 -1 */
				if(file==null)
				{
					return -1;
				}
				
			} catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
				return -1;            /* 出现了异常也返回-1 */
			}
			finally
			{
				try{
					inputstream.close();
				}catch (IOException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}
		
		return 1;
	}

}


你可能感兴趣的:(多线程,android,网络访问)