Notification使用详解之四:由后台服务向Activity发送进度信息

来源:互联网 发布:app软件著作权范本 编辑:程序博客网 时间:2024/04/29 00:20

上次讲到了如何在Activity中监听后台服务的进度信息,实现的方式是让Activity与后台服务绑定,通过中间对象Binder的实例操作后台服务。从效果上来讲,这种方式是可行的,不过这种实现有个缺点,那就是Activity的任务太重了,为了监听服务的状态,我们不得不绑定服务,然后还需不断地定时的获取最新的进度,我们为何不换一下形式呢,让Service主动将进度发送给Activity,我们在Activity中只需拿到进度数据,然后更新UI界面。这种新形式就像上次结尾提到的,就像两个男人同时喜欢一个女人,都通过自己的手段试图从那个女人那里获取爱情,现在我们要让那个女人变为主动方,将爱情同时传递给那两个男人。

要实现以上方式,我们需要用到BroadcastReceiver,如果不太了解的朋友们,可以查阅相关资料补充一下。

关于整个流程的的截图,我在这里就不在贴出了,大家可以参看Notification详解之三的流程截图。布局文件也没有变化,所以这里也不在贴出。

我们主要看一下MainActivity、DownloadService、FileMgrActivity这几个组件的实现形式。

首先是MainActivity:

[java] view plaincopy
  1. package com.scott.notification;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.IntentFilter;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.widget.TextView;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     private MyReceiver receiver;  
  15.     private TextView text;  
  16.   
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.         text = (TextView) findViewById(R.id.text);  
  22.           
  23.         receiver = new MyReceiver();  
  24.         IntentFilter filter = new IntentFilter();  
  25.         filter.addAction("android.intent.action.MY_RECEIVER");  
  26.         //注册  
  27.         registerReceiver(receiver, filter);  
  28.     }  
  29.       
  30.     @Override  
  31.     protected void onDestroy() {  
  32.         super.onDestroy();  
  33.         //不要忘了这一步  
  34.         unregisterReceiver(receiver);  
  35.     }  
  36.   
  37.     public void start(View view) {  
  38.         Intent intent = new Intent(this, DownloadService.class);  
  39.         //这里不再使用bindService,而使用startService  
  40.         startService(intent);  
  41.     }  
  42.   
  43.     /** 
  44.      * 广播接收器 
  45.      * @author user 
  46.      * 
  47.      */  
  48.     private class MyReceiver extends BroadcastReceiver {  
  49.   
  50.         @Override  
  51.         public void onReceive(Context context, Intent intent) {  
  52.             Bundle bundle = intent.getExtras();  
  53.             int progress = bundle.getInt("progress");  
  54.             text.setText("downloading..." + progress + "%");  
  55.         }  
  56.     }  
  57. }  

上面的代码中,我们的MyReceiver类是继承了BroadcastReceiver,在onReceive方法中,定义了收到进度信息并更新UI的逻辑,在onCreate中,我们注册了这个接受者,并指定action为android.intent.action.MY_RECEIVER,如此一来,如果其他组件向这个指定的action发送消息,我们就能够接收到;另外要注意的是,不要忘了在Activity被摧毁的时候调用unregisterReceiver取消注册。

然后再来看一下DownloadService有什么变化:

[java] view plaincopy
  1. package com.scott.notification;  
  2.   
  3. import android.app.Notification;  
  4. import android.app.NotificationManager;  
  5. import android.app.PendingIntent;  
  6. import android.app.Service;  
  7. import android.content.Context;  
  8. import android.content.Intent;  
  9. import android.os.Handler;  
  10. import android.os.IBinder;  
  11. import android.os.Message;  
  12. import android.widget.RemoteViews;  
  13.   
  14. public class DownloadService extends Service {  
  15.   
  16.     private static final int NOTIFY_ID = 0;  
  17.     private boolean cancelled;  
  18.       
  19.     private Context mContext = this;  
  20.     private NotificationManager mNotificationManager;  
  21.     private Notification mNotification;  
  22.       
  23.     private Handler handler = new Handler() {  
  24.         public void handleMessage(android.os.Message msg) {  
  25.             switch (msg.what) {  
  26.             case 1:  
  27.                 int rate = msg.arg1;  
  28.                 if (rate < 100) {  
  29.                     //更新进度  
  30.                     RemoteViews contentView = mNotification.contentView;  
  31.                     contentView.setTextViewText(R.id.rate, rate + "%");  
  32.                     contentView.setProgressBar(R.id.progress, 100, rate, false);  
  33.                 } else {  
  34.                     //下载完毕后变换通知形式  
  35.                     mNotification.flags = Notification.FLAG_AUTO_CANCEL;  
  36.                     mNotification.contentView = null;  
  37.                     Intent intent = new Intent(mContext, FileMgrActivity.class);  
  38.                     // 告知已完成  
  39.                     intent.putExtra("completed""yes");  
  40.                     //更新参数,注意flags要使用FLAG_UPDATE_CURRENT  
  41.                     PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);  
  42.                     mNotification.setLatestEventInfo(mContext, "下载完成""文件已下载完毕", contentIntent);  
  43.                 }  
  44.   
  45.                 // 最后别忘了通知一下,否则不会更新  
  46.                 mNotificationManager.notify(NOTIFY_ID, mNotification);  
  47.                   
  48.                 if (rate >= 100) {  
  49.                     stopSelf(); //停止服务  
  50.                 }  
  51.                   
  52.                 break;  
  53.             case 0:  
  54.                 // 取消通知  
  55.                 mNotificationManager.cancel(NOTIFY_ID);  
  56.                 break;  
  57.             }  
  58.         };  
  59.     };  
  60.       
  61.     @Override  
  62.     public void onCreate() {  
  63.         super.onCreate();  
  64.         mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);  
  65.     }  
  66.       
  67.     @Override  
  68.     public void onStart(Intent intent, int startId) {  
  69.         super.onStart(intent, startId);  
  70.           
  71.         int icon = R.drawable.down;  
  72.         CharSequence tickerText = "开始下载";  
  73.         long when = System.currentTimeMillis();  
  74.         mNotification = new Notification(icon, tickerText, when);  
  75.   
  76.         // 放置在"正在运行"栏目中  
  77.         mNotification.flags = Notification.FLAG_ONGOING_EVENT;  
  78.   
  79.         RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.download_notification_layout);  
  80.         contentView.setTextViewText(R.id.fileName, "AngryBird.apk");  
  81.         // 指定个性化视图  
  82.         mNotification.contentView = contentView;  
  83.   
  84.         Intent intnt = new Intent(this, FileMgrActivity.class);  
  85.         PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intnt, PendingIntent.FLAG_UPDATE_CURRENT);  
  86.         // 指定内容意图  
  87.         mNotification.contentIntent = contentIntent;  
  88.   
  89.         mNotificationManager.notify(NOTIFY_ID, mNotification);  
  90.           
  91.         new Thread() {  
  92.             public void run() {  
  93.                 startDownload();  
  94.             };  
  95.         }.start();  
  96.     }  
  97.       
  98.     @Override  
  99.     public void onDestroy() {  
  100.         super.onDestroy();  
  101.         cancelled = true;   //停止下载线程  
  102.     }  
  103.       
  104.     private void startDownload() {  
  105.         cancelled = false;  
  106.         int rate = 0;  
  107.         while (!cancelled && rate < 100) {  
  108.             try {  
  109.                 //模拟下载进度  
  110.                 Thread.sleep(500);  
  111.                 rate = rate + 5;  
  112.             } catch (InterruptedException e) {  
  113.                 e.printStackTrace();  
  114.             }  
  115.             Message msg = handler.obtainMessage();  
  116.             msg.what = 1;  
  117.             msg.arg1 = rate;  
  118.             handler.sendMessage(msg);  
  119.               
  120.             //发送特定action的广播  
  121.             Intent intent = new Intent();  
  122.             intent.setAction("android.intent.action.MY_RECEIVER");  
  123.             intent.putExtra("progress", rate);  
  124.             sendBroadcast(intent);  
  125.         }  
  126.         if (cancelled) {  
  127.             Message msg = handler.obtainMessage();  
  128.             msg.what = 0;  
  129.             handler.sendMessage(msg);  
  130.         }  
  131.     }  
  132.       
  133.     @Override  
  134.     public IBinder onBind(Intent intent) {  
  135.         return null;  
  136.     }  
  137. }  

可以看到,我们在onBind方法里不在返回自定义的Binder实例了,因为现在的Service和Activitys之间并没有绑定关系了,他们是独立的;在下载过程中,我们会调用sendBroadcast方法,向指定的action发送一个附带有进度信息的intent,这样的话,所有注册过action为android.intent.action.MY_RECEIVER的Activity都能收到这条进度消息了。

最后再来看一下FileMgrActivity:

[java] view plaincopy
  1. package com.scott.notification;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.IntentFilter;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.widget.ProgressBar;  
  11.   
  12. public class FileMgrActivity extends Activity {  
  13.       
  14.     private MyReceiver receiver;  
  15.     private ProgressBar progressBar;  
  16.       
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.filemgr);  
  21.         progressBar = (ProgressBar) findViewById(R.id.progress);  
  22.           
  23.         if ("yes".equals(getIntent().getStringExtra("completed"))) {  
  24.             progressBar.setProgress(100);  
  25.         }  
  26.           
  27.         receiver = new MyReceiver();  
  28.         IntentFilter filter = new IntentFilter();  
  29.         filter.addAction("android.intent.action.MY_RECEIVER");  
  30.         //注册  
  31.         registerReceiver(receiver, filter);  
  32.     }  
  33.       
  34.     public void cancel(View view) {  
  35.         Intent intent = new Intent(this, DownloadService.class);  
  36.         stopService(intent);  
  37.     }  
  38.       
  39.     @Override  
  40.     protected void onDestroy() {  
  41.         super.onDestroy();  
  42.         //不要忘了这一步  
  43.         unregisterReceiver(receiver);  
  44.     }  
  45.       
  46.     /** 
  47.      * 广播接收器 
  48.      * @author user 
  49.      * 
  50.      */  
  51.     private class MyReceiver extends BroadcastReceiver {  
  52.   
  53.         @Override  
  54.         public void onReceive(Context context, Intent intent) {  
  55.             Bundle bundle = intent.getExtras();  
  56.             int progress = bundle.getInt("progress");  
  57.             progressBar.setProgress(progress);  
  58.         }  
  59.     }  
  60.       
  61. }  

我们发现,FileMgrActivity的模式和MainActivity差不多,也是注册了相同的广播接收者,对于DownloadService来说自己是广播基站,MainActivity和FileMgrActivity就是听众,信号能够同时到达多个听众,对于代码而言,与之前的代码比较一下,发现简洁了许多,显然这种方式更好一些。

对于我们上面提到的男女关系,DownloadService就是那个女人,然后两个男人将自己的手机号告知了女人,等于注册了接收器,然后女人将短信群发给两个男人。不过在这种情况下,两个男人互相都不知道对方的存在,以为女人深深的爱着自己,等到发现一切的时候,就是痛苦的时候。相信大家如果遇到这种情况都会很痛苦吧,至于你们信不信,我反正是信的。哈哈。

其实关于Notification的讲解最后两篇涉及到Notification的不多,主要是围绕Notification做一些实际的应用示例,希望对于朋友们平时遇到的问题会有所帮助,如果这方面有了新的研究总结,我会再及时更新的,谢谢大家。