AIDL_Service_多线程_通知_Demo



看标题就知道啦.

粘贴service部分出来.

package com.docin.download;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.RemoteViews;

public class TestService extends Service
{

	boolean									isStop				= false;
	private BookDownloaderInterface.Stub	mBind;
	String									fileEx, fileNa;

	// /通知/
	public NotificationManager				mNotificationManager;
	private HashMap<String, Object>			myDownloadingName	= new HashMap<String, Object>();

	@Override
	public IBinder onBind(Intent intent)
	{
		return mBind;
	}

	public void onCreate()
	{

		Log.i("TAG", "Services onCreate");
		super.onCreate();
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		initBind();

	}

	public void notificationDownload(int flag, int value, String name)
	{
		Notification notification = null;
		int notificationId = 0;
		if (flag == 0)
		{
			notification = createDownloadProgressNotification(name);
		}
		else
			if (flag == 1)
			{
				notification = startDownloadProgressNotification(name, value);
			}
			else
				if (flag == 2)
				{
					notification = finishDownloadFinishNotification(name);
				}
		if (!myDownloadingName.containsKey(name))
		{
			notificationId = myDownloadingName.size() + 1;
			myDownloadingName.put(name, notificationId);
		}
		else
		{
			notificationId = (Integer) myDownloadingName.get(name);
		}
		mNotificationManager.notify(notificationId, notification);

	}

	private Notification finishDownloadFinishNotification(String name)
	{

		final String tickerText = name;
		final String contentText = "完成";
		final Notification notification = new Notification(
				android.R.drawable.stat_sys_download_done, tickerText,
				System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		final Intent intent = new Intent(this, ImageViewActivity.class);
		intent.putExtra("imgname", name);
		// 填加下行代码实现Notification的unique
		intent.setData((Uri.parse("custom://" + System.currentTimeMillis())));
		final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				intent, 0);
		notification.setLatestEventInfo(getApplicationContext(), name,
				contentText, contentIntent);
		return notification;
	}

	private Notification startDownloadProgressNotification(String title,
			int progress)
	{

		final RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.download_notification);
		;

		if (progress < 0)
		{
			contentView.setTextViewText(
					R.id.download_notification_progress_text, "");
			contentView.setProgressBar(R.id.download_notification_progress_bar,
					100, 0, true);
		}
		else
		{
			contentView.setTextViewText(
					R.id.download_notification_progress_text, "" + progress
							+ "%");
			contentView.setProgressBar(R.id.download_notification_progress_bar,
					100, progress, false);
		}
		final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(), 0);
		final Notification notification = new Notification();
		notification.icon = android.R.drawable.stat_sys_download;
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.contentView = contentView;
		notification.contentIntent = contentIntent;

		return notification;
	}

	private Notification createDownloadProgressNotification(String title)
	{
		final RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.download_notification);
		contentView.setTextViewText(R.id.download_notification_title, title);
		contentView.setTextViewText(R.id.download_notification_progress_text,
				"");
		contentView.setProgressBar(R.id.download_notification_progress_bar,
				100, 0, true);

		final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(), 0);

		final Notification notification = new Notification();
		notification.icon = android.R.drawable.stat_sys_download;
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.contentView = contentView;
		notification.contentIntent = contentIntent;

		return notification;
	}

	public void initBind()
	{
		mBind = new BookDownloaderInterface.Stub()
		{
			@Override
			public void beingDownload(String url, String savePath)
					throws RemoteException
			{
				// TODO Auto-generated method stub
				downloadFile(url, savePath);
			}
		};
	}

	public void onStart(Intent intent, int startId)
	{
		Log.i("TAG", "Services onStart");
		super.onStart(intent, startId);

	}

	private final ExecutorService	executorService	= Executors
															.newFixedThreadPool(5);

	public void downloadFile(final String url, final String savePath)
	{

		executorService.submit(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					down_file(url, savePath);
				} catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void onDestroy()
	{

		Log.i("TAG", "Services onDestory");
		isStop = true;// 即使service销毁线程也不会停止,所以这里通过设置isStop来停止线程
		super.onDestroy();

	}

	// 接收线程发送出来的数据,标识
	private Handler	handler	= new Handler()
							{
								public void handleMessage(Message msg)
								{
									if (!Thread.currentThread().isInterrupted())
									{
										switch (msg.what)
										{
											case 0:
												notificationDownload(0,
														msg.arg1,
														(String) msg.obj);
												break;
											case 1:
												notificationDownload(1,
														msg.arg1,
														(String) msg.obj);
												break;
											case 2:
												notificationDownload(2,
														msg.arg1,
														(String) msg.obj);
												break;
											default:
												break;
										}
									}
								}

							};

	/**
	 * 下载文件方法
	 * 
	 * @param url
	 *            文件在服务器的url
	 * @param path
	 *            保存在本地的绝对目录
	 * @throws IOException
	 */
	public void down_file(String url, String path) throws IOException
	{
		String filename = "";
		int currentValue = 0;
		int fileSize;
		int downLoadFileSize;
		filename = url.substring(url.lastIndexOf("/") + 1);
		URL myURL = new URL(url);
		URLConnection conn = myURL.openConnection();
		conn.connect();
		InputStream is = conn.getInputStream();
		fileSize = conn.getContentLength();
		if (fileSize <= 0)
			throw new RuntimeException("无法获知文件大小 ");
		if (is == null)
			throw new RuntimeException("stream is null");
		FileOutputStream fos = new FileOutputStream(path + filename);
		byte buf[] = new byte[1024 * 10];
		downLoadFileSize = 0;

		sendMsg(0, filename, 0);
		do
		{
			int numread = is.read(buf);
			if (numread == -1)
			{
				break;
			}
			fos.write(buf, 0, numread);
			downLoadFileSize += numread;
			currentValue = (int) (((double) downLoadFileSize / fileSize) * 100);
			sendMsg(currentValue, filename, 1);
		} while (true);
		sendMsg(fileSize, filename, 2);
		try
		{
			is.close();
		} catch (Exception ex)
		{
			Log.e("tag", "error: " + ex.getMessage(), ex);
		}

	}

	/**
	 * 发送Message
	 * 
	 * @param flag
	 *            what的值
	 */

	private void sendMsg(int currentValue, String name, int flag)
	{
		Message msg = new Message();
		msg.what = flag;
		msg.arg1 = currentValue;
		msg.obj = name;

		handler.sendMessage(msg);
	}

}

................................................................................





http://download.csdn.net/detail/synwith/3776070

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值