Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發之根據Service的生命周期特點後台連接網絡下載圖片(源代碼分享)

Android開發之根據Service的生命周期特點後台連接網絡下載圖片(源代碼分享)

編輯:關於Android編程

上一章講到Service在後台啟動後不會自動銷毀掉,其銷毀的方式有兩種一個是在外部使用stopService()方法,一個就是在繼承Service的類下調用stopSelf(),那麼應該何時調用stopself()方法呢,如果不調用的話,service在後台會一直處在連接網絡的狀態,其內耗是可想而知的。這篇博文就會向大家介紹如果使用handle的信息傳送機制來停止service的後台運行。‘

MainActivity

package com.example.f21_service01;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
   private Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button=(Button)this.findViewById(R.id.button1);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(MainActivity.this,DownLoadService.class);
				startService(intent);//通過intent啟動service
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

MainActivity中的代碼很簡單,通過按下按鈕來啟動一個service,在這裡還得強調一下service要記得在清單文件中聲明,要不然會報錯的。

DownloadService的代碼

package com.example.f21_service01;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class DownLoadService extends Service {
	private static final String path = "http://my.csdn.net/u013900875";
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				stopSelf(); //當系統接收到消息後,關閉service
			}

		};
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		new Thread(new MyThread()).start();//啟動線程
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	public class MyThread implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(path);
			try {
				HttpResponse httpResponse = client.execute(httpPost);
				byte[] result = EntityUtils.toByteArray(httpResponse
						.getEntity());//使用http協議下載圖片
				boolean flag = SDcardtoFile.WriteToFile("hello", result);//當成功寫入內存卡後,將標志設為true
				if (flag) {
					
					handler.sendEmptyMessage(1);//通過handler發送消息
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}

在startCommand()啟動下載的線程,當下載完成後並且成功寫入內存卡後,將flag置位true,通過handler的sendMessage()方法發送,然後調用stopself(),那為什麼不直接調用這個方法呢,因為調用這個方法service的停止時間是不確定的,後面的代碼還是會執行的。

最後再來回顧下之前前的sdcard的存入方法的書寫

package com.example.f21_service01;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

public class SDcardtoFile {
	public static boolean WriteToFile(String name, byte[] data) {
		boolean flag = false;
		String state = Environment.getExternalStorageState();
		FileOutputStream fileOutputStream = null;
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			File file = new File(Environment.getExternalStorageDirectory(),
					name);
			try {
				fileOutputStream=new FileOutputStream(file);
				try {
					fileOutputStream.write(data, 0, data.length);
					flag=true;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if (fileOutputStream!=null) {
					try {
						fileOutputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
		}
		return flag;
	}

}




  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved