动态改变service内容添加下载信息
最近的项目中,有一个需求是 【后台下载+多线程+Notificaton进度条】的应用。要求有一个Service做下载服务,Notification中显示一进度条,进度条由Service来更新。
花了个把小时在网上找代码,没有一个完美的方案,最后根据片段信息,自己实现了。贴出来分享一下。
思路:
- 1. 有一个提供队列下载的Service
- 2. 该Service可以绑定,绑定的时候返回本身实例
- 3. 该Service提供方法给绑定了该Service的Activity,Activity可以调用Service的提供的方法,给Service添加队列
- 4. 该Service提供了当前下载队列的信息,信息包括下载的名称,下载进度,Activity通过接口读取队列信息用于操作,如:取消
实现:
1. 队列类
- public classDownLoadQueue{
- public int id; //队列id , 该id标识了一条下载线程和Notification
- public Stringname; // 队列名称,用于显示在Notification中
- public int progress = 0; //进度,一个0-100之前的整数,标识百分比
- public boolean isCancel = fale; //是否已经取消,该开关用于取消下载
2. Service类:
- public classDownloadService extends Service{
- private MapdownLoadQueue; //下载队列,格式:
- private BinderserviceBinder = new DownLoadServiceBinder();
- // Activity绑定后,会自动条用这个方法
- @Override
- public IBinderonBind(Intentintent)
- {
- Log.d("DownloadService", "onBind");
- return serviceBinder;
- }
- ....
- private void startDownLoad(DownLoadQueuequeue){
- new Thread(){
- public void run(){
- //进行下载工作,这里需要更新downLoadQueue中对应的queue的进度信息
- //使用Handler更新notification信息
- ....
- }
- }.start();
- }
- public void addQueue(DownLoadQueuequeue){
- this.downLoadQueue.add(queue.id,queue);
- this.startDownLoad(queue);
- }
- public MapgetQueueList(){
- return this.downLoadQueue;
- }
- public classpublic DownLoadServiceBinder extends Binder{
- public DownloadServicegetService(){
- return DownloadService.this;
- }
- }
3. Activity类:
- public classDownLoadActivity{
- private Handlerhandler = new Handler();
- private DownloadServicedownLoadService;
- private ServiceConnectionserviceConnection = new ServiceConnection()
- {
- // 连接服务失败后,该方法被调用
- @Override
- public void onServiceDisconnected(ComponentNamename)
- {
- downLoadService = null;
- Toast.makeText(DownLoadActivity.this, "Service Failed.", Toast.LENGTH_LONG).show();
- }
- // 成功连接服务后,该方法被调用。在该方法中可以获得downLoadService对象
- @Override
- public void onServiceConnected(ComponentNamename, IBinderservice)
- {
- // 获得downLoadService对象
- downLoadService = ((DownLoadService.DownLoadServiceBinder) service).getService();
- Toast.makeText(DownLoadActivity.this, "Service Connected.", Toast.LENGTH_LONG).show();
- }
- };
- @Override
- public void onCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- IntentserviceIntent = new Intent(DownLoadActivity.this,DownloadService.class);
- bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
- startService(serviceIntent);
- .....
- }
- private void startDownLoad(){
- DownLoadQueuequeue = new DownLoadQueue();
- queue.id = 1;
- queue.name = "愤怒的小鸟"
- ...
- downLoadService.addDownLoad(queue);
- ....
- }
- @Override
- public void onDestroy(){
- super.onDestroy();
- unbindService(new Intent(DownLoadActivity.this,DownloadService.class));
- }
4. 在Service中更新Notification时,不能过于频繁,否则会造成卡机。notification使用RemoteView来自定义Notification,加入进度条加入各种说明文字,等等。
以上文字只是简单的提及了一些思路。在项目中已经实现。下次修改完善后贴上来分享。希望能够将该功能做成一个独立的Service供大家在项目中嵌入使用