android开发----service下载图片

本文介绍两种在Android中实现后台下载图片的方法:一是通过继承Service并使用Handler处理UI更新;二是利用IntentService简化下载流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:通过DownLoadService继承service类。如果在主线程中下载图片,会造成主线程的阻塞,所以需要在DownLoadService中创建线程,并且将数据传输到主线程,进行更新ui操作,那么android中那个知识点可以跨线程呢?答案就是Handler

MainActivity.java

package com.example.android_service_download;

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

public class MainActivity extends Activity {
	private Button button1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button1 = (Button) this.findViewById(R.id.button1);
		button1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, DownLoadService.class);
				startService(intent);
			}
		});
	}

	@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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

DownLoadService.java

package com.example.android_service_download;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class DownLoadService extends Service {
	private final String imagePath = "https://www.baidu.com/img/bd_logo1.png";
	private NotificationCompat.Builder builder;
	private NotificationManager manager;
	
	private Handler handler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) {
				stopSelf();
				Toast.makeText(getApplicationContext(), "下载完成!", Toast.LENGTH_SHORT).show();
			}
			
			builder.setProgress(100, msg.arg1, false);
			manager.notify(1001, builder.build());
		};
	};
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		builder = new NotificationCompat.Builder(getApplicationContext());
		builder.setSmallIcon(R.drawable.ic_launcher);
		builder.setContentTitle("DownLoad");
		builder.setContentText("downLoad...");
		manager.notify(1001, builder.build());
	}
	
	/**
	 * 需要下载网络图片,下载完成需要停止service
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		new Thread(new MyTread()).start();
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	public class MyTread implements Runnable  {
		@Override
		public void run() {
			ByteArrayOutputStream stream = null;
			try {
				//建立连接
				URL url = new URL(imagePath);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("POST");
				
				//连接
				conn.connect();
				
				//获取相应状态
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					/*InputStream is = conn.getInputStream();
					
					Bitmap bitmap = BitmapFactory.decodeStream(is);
					stream = new ByteArrayOutputStream();
					bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
					byte[] byteArray = stream.toByteArray();
					
					boolean flag = SDCardUtils.downLoadPicture(getApplicationContext(), "aa.png", byteArray);
					if (flag) {
						handler.sendEmptyMessage(1);
					}*/
					
					InputStream is1 = null;
					stream = new ByteArrayOutputStream();
					//获得文件中长度
					int length = conn.getContentLength();
					System.out.println("---->>"+length);
					int sum_length = 0; //每次获取的大小
					int len = 0;
					
					byte[] data = new byte[1024];
					try {
						is1 = conn.getInputStream();
						while ((len = is1.read(data)) > 0) {
							stream.write(data, 0, len);
							sum_length += len;
							
							//计算每次下载文件大小的刻度
							int value = (int) (sum_length/(float)length * 100);
							Message message = Message.obtain();
							message.arg1 = value;
							handler.sendMessage(message);
						}
						if (SDCardUtils.downLoadPicture(getApplicationContext(), "123.png", stream.toByteArray())) {
							handler.sendEmptyMessage(1);
						}
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
				
			}catch (Exception e) {
				e.printStackTrace();
			} finally {
				if(stream != null) {
					try {
						stream.close();
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
SDCardUtils.java

package com.example.android_service_download;

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

import android.content.Context;

public class SDCardUtils {

	public static boolean downLoadPicture(Context context, String name, byte[] buffer) {
		boolean flag = false;
		FileOutputStream outputStream = null;
		
		try {
			outputStream = context.getApplicationContext().openFileOutput(name, Context.MODE_PRIVATE);
			outputStream.write(buffer, 0, buffer.length);
			flag = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
}


方法二:让DownLoadService继承IntentService,通过onHandleIntent方法来下载数据,原理就是对上述方法的封装

MainActivity.java

package com.example.android_service_intentservice;

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

import android.content.Context;

public class SDCardUtils {

	public static boolean downLoadPicture(Context context, String name, byte[] buffer) {
		boolean flag = false;
		FileOutputStream outputStream = null;
		
		try {
			outputStream = context.getApplicationContext().openFileOutput(name, Context.MODE_PRIVATE);
			outputStream.write(buffer, 0, buffer.length);
			flag = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
}

DownLoadService.java

package com.example.android_service_intentservice;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class DownLoadService extends IntentService {
	private final String imagePath = "https://www.baidu.com/img/bd_logo1.png";

	public DownLoadService() {
		super("");
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		ByteArrayOutputStream stream = null;
		try {
			//建立连接
			URL url = new URL(imagePath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			
			//连接
			conn.connect();
			
			//获取相应状态
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				stream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
				byte[] byteArray = stream.toByteArray();
				
				boolean flag = SDCardUtils.downLoadPicture(getApplicationContext(), "aa.png", byteArray);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(stream != null) {
				try {
					stream.close();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
	
	}

}
SDCardUtils.java

package com.example.android_service_intentservice;

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

import android.content.Context;

public class SDCardUtils {

	public static boolean downLoadPicture(Context context, String name, byte[] buffer) {
		boolean flag = false;
		FileOutputStream outputStream = null;
		
		try {
			outputStream = context.getApplicationContext().openFileOutput(name, Context.MODE_PRIVATE);
			outputStream.write(buffer, 0, buffer.length);
			flag = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值