WEB开发网
开发学院手机开发Android 开发 Android通过AIDL实现下载进程通信 阅读

Android通过AIDL实现下载进程通信

 2012-11-08 19:04:01 来源:WEB开发网   
核心提示:private final static int UPDATE_NOTIFY_COMPLETE = 4;//handler 标识:更新进度条到完成状态(100%)private final static int DOWNLOAD_EXCEPTION_NOTIFY = 6;//handler 标识:下载发送异常,如IO异
private final static int UPDATE_NOTIFY_COMPLETE = 4; //handler 标识:更新进度条到完成状态(100%)
private final static int DOWNLOAD_EXCEPTION_NOTIFY = 6; //handler 标识:下载发送异常,如IO异常
private final static int DOWNLOAD_FILE_SIZE = 1024*10; //下载块大小:1K

private NotificationManager nManager; //状态栏提醒管理器
private Map<Integer, Queue> queueList; //队列列表

@Override
public IBinder onBind(Intent arg0) {
// 返回IDownLoadService.aidl接口实例
return mBinder;
}

@Override
public void onCreate() {
// 初始化
super.onCreate();
nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
queueList = new HashMap<Integer, Queue>();
}

@Override
public void down(Queue queue) throws RemoteException {
// 添加一个队列到下载服务中
startDownLoad(queue);
}

/**
* 新开一个下载进程
**/
private void startDownLoad(final Queue queue){
if(queue.isCancel()){
//如果已经取消则不进行
return;
}
this.queueList.put(queue.getId(), queue); //添加到队列
new Thread(){
@Override
public void run(){
downLoad(queue); //下载操作
}

}.start();
}

/**
* 下载具体方法
**/
private void downLoad(Queue queue){

Notification notify = null; //创建一个notify

//创建一个新的notify实例,如果队列定义了downingIntent,则加入该intent到notify,
//否则指向服务本身
if(queue.getDowningIntent()!=null && !queue.getDowningIntent().equals("")){
notify = newNotification(queue.getName(),
new Intent(queue.getDowningIntent()),
Notification.FLAG_NO_CLEAR, 100);
}else{
notify = newNotification(queue.getName(),
new Intent(DownLoadService.this,DownLoadService.class),
Notification.FLAG_NO_CLEAR, 100);
}

//更新notify进度为0
updateProgressBar(queue.getId(), UPDATE_NOTIFY_PROGRESS, 0,
notify);

//定义URL下载用的一些变量
HttpURLConnection urlConn = null;
InputStream inputStream = null;
File file = new File(queue.getSavePath());
new File(file.getParent()).mkdirs(); //创建目录
OutputStream output = null;

try {
URL url = new URL(queue.getUrl());
urlConn = (HttpURLConnection) url.openConnection();
inputStream = urlConn.getInputStream();
output = new FileOutputStream(file);
byte[] buffer = new byte[DOWNLOAD_FILE_SIZE];

long length = urlConn.getContentLength();

queueList.get(queue.getId()).setFileLength(length); //更新队列中Queue的文件长度

long downSize = 0;
float totalSize = length;

int percent = 0;
do {
int numread = inputStream.read(buffer);
if (numread == -1) {
break;
}
output.write(buffer, 0, numread);

downSize += numread;
queueList.get(queue.getId()).setDownSize(downSize); //更新队列中Queue的已下载大小

int nowPercent = (int) ((downSize / totalSize) * 100);

//如果百分比有变动则更新进度条
if (nowPercent > percent) {

上一页  1 2 3 4 5 6 7 8 9  下一页

Tags:Android 通过 AIDL

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接