DownloadTest代码思路:
1.首先,下载操作应该是后台操作,因此定义一个Downloadservice去进行全部的download,pause,cancel等操作,并且为了防止service被杀死,将此service设定为前台service。
2.其次,所有和下载有关的操作都是耗时操作,因此要定义一个Asynctask去真正执行startdownload(位于doinbackground),pausedownload,canceldownload等操作。
3.一般正常逻辑,当下载任务开始,暂停,取消等操作执行时,都应该以Toast的和Notification的形式提示给用户。尤其是Notification,可以用进度条来显示下载的过程。
而asynctask是不能更改UI的,因此要定义一个interface(具体在DownloadService中实现),使AsyncTask能够回调修改UI.
4.最后,既然要使用Activity去启动Service,使用bindService的方式去启动Service。在DownloadBinder中去调用DownloadTask。
使用bindService启动Service是的Activity和Service进行通信的步骤:
1.在Service中:
定义 private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
......
}
重写
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
2.在Activity中:
定义
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
启动
bindService(intent, connection, BIND_AUTO_CREATE);
1.首先,下载操作应该是后台操作,因此定义一个Downloadservice去进行全部的download,pause,cancel等操作,并且为了防止service被杀死,将此service设定为前台service。
2.其次,所有和下载有关的操作都是耗时操作,因此要定义一个Asynctask去真正执行startdownload(位于doinbackground),pausedownload,canceldownload等操作。
3.一般正常逻辑,当下载任务开始,暂停,取消等操作执行时,都应该以Toast的和Notification的形式提示给用户。尤其是Notification,可以用进度条来显示下载的过程。
而asynctask是不能更改UI的,因此要定义一个interface(具体在DownloadService中实现),使AsyncTask能够回调修改UI.
4.最后,既然要使用Activity去启动Service,使用bindService的方式去启动Service。在DownloadBinder中去调用DownloadTask。
使用bindService启动Service是的Activity和Service进行通信的步骤:
1.在Service中:
定义 private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
......
}
重写
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
2.在Activity中:
定义
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
启动
bindService(intent, connection, BIND_AUTO_CREATE);
至此,在Activity中便可以通过downloadBinder来进行对Service的操作。
代码地址https://git.coding.net/jasson_wrd/DownloadTest.git