上次講到了如何在Activity中監聽後臺服務的進度信息,實現的方式是讓Activity與後臺服務綁定,經過中間對象Binder的實例操做 後臺服務。從效果上來說,這種方式是可行的,不過這種實現有個缺點,那就是Activity的任務過重了,爲了監聽服務的狀態,咱們不得不綁定服務,而後 還需不斷地定時的獲取最新的進度,咱們爲什麼不換一下形式呢,讓Service主動將進度發送給Activity,咱們在Activity中只需拿到進度數 據,而後更新UI界面。這種新形式就像上次結尾提到的,就像兩個男人同時喜歡一個女人,都經過本身的手段試圖從那個女人那裏獲取愛情,如今咱們要讓那個女 人變爲主動方,將愛情同時傳遞給那兩個男人。 java
要實現以上方式,咱們須要用到BroadcastReceiver,若是不太瞭解的朋友們,能夠查閱相關資料補充一下。 android
關於整個流程的的截圖,我在這裏就不在貼出了,你們能夠參看Notification詳解之三的流程截圖。佈局文件也沒有變化,因此這裏也不在貼出。 app
咱們主要看一下MainActivity、DownloadService、FileMgrActivity這幾個組件的實現形式。 ide
首先是MainActivity: 佈局
- package com.scott.notification;
-
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
-
- public class MainActivity extends Activity {
-
- private MyReceiver receiver;
- private TextView text;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- text = (TextView) findViewById(R.id.text);
-
- receiver = new MyReceiver();
- IntentFilter filter = new IntentFilter();
- filter.addAction("android.intent.action.MY_RECEIVER");
- //註冊
- registerReceiver(receiver, filter);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- //不要忘了這一步
- unregisterReceiver(receiver);
- }
-
- public void start(View view) {
- Intent intent = new Intent(this, DownloadService.class);
- //這裏再也不使用bindService,而使用startService
- startService(intent);
- }
-
- /**
- * 廣播接收器
- * @author user
- *
- */
- private class MyReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- Bundle bundle = intent.getExtras();
- int progress = bundle.getInt("progress");
- text.setText("downloading..." + progress + "%");
- }
- }
- }
上 面的代碼中,咱們的MyReceiver類是繼承了BroadcastReceiver,在onReceive方法中,定義了收到進度信息並更新UI的邏 輯,在onCreate中,咱們註冊了這個接受者,並指定action爲android.intent.action.MY_RECEIVER,如此一 來,若是其餘組件向這個指定的action發送消息,咱們就可以接收到;另外要注意的是,不要忘了在Activity被摧毀的時候調用 unregisterReceiver取消註冊。 this
而後再來看一下DownloadService有什麼變化: spa
- package com.scott.notification;
-
- 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.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.widget.RemoteViews;
-
- public class DownloadService extends Service {
-
- private static final int NOTIFY_ID = 0;
- private boolean cancelled;
-
- private Context mContext = this;
- private NotificationManager mNotificationManager;
- private Notification mNotification;
-
- private Handler handler = new Handler() {
- public void handleMessage(android.os.Message msg) {
- switch (msg.what) {
- case 1:
- int rate = msg.arg1;
- if (rate < 100) {
- //更新進度
- RemoteViews contentView = mNotification.contentView;
- contentView.setTextViewText(R.id.rate, rate + "%");
- contentView.setProgressBar(R.id.progress, 100, rate, false);
- } else {
- //下載完畢後變換通知形式
- mNotification.flags = Notification.FLAG_AUTO_CANCEL;
- mNotification.contentView = null;
- Intent intent = new Intent(mContext, FileMgrActivity.class);
- // 告知已完成
- intent.putExtra("completed", "yes");
- //更新參數,注意flags要使用FLAG_UPDATE_CURRENT
- PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
- mNotification.setLatestEventInfo(mContext, "下載完成", "文件已下載完畢", contentIntent);
- }
-
- // 最後別忘了通知一下,不然不會更新
- mNotificationManager.notify(NOTIFY_ID, mNotification);
-
- if (rate >= 100) {
- stopSelf(); //中止服務
- }
-
- break;
- case 0:
- // 取消通知
- mNotificationManager.cancel(NOTIFY_ID);
- break;
- }
- };
- };
-
- @Override
- public void onCreate() {
- super.onCreate();
- mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
- }
-
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
-
- int icon = R.drawable.down;
- CharSequence tickerText = "開始下載";
- long when = System.currentTimeMillis();
- mNotification = new Notification(icon, tickerText, when);
-
- // 放置在"正在運行"欄目中
- mNotification.flags = Notification.FLAG_ONGOING_EVENT;
-
- RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.download_notification_layout);
- contentView.setTextViewText(R.id.fileName, "AngryBird.apk");
- // 指定個性化視圖
- mNotification.contentView = contentView;
-
- Intent intnt = new Intent(this, FileMgrActivity.class);
- PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intnt, PendingIntent.FLAG_UPDATE_CURRENT);
- // 指定內容意圖
- mNotification.contentIntent = contentIntent;
-
- mNotificationManager.notify(NOTIFY_ID, mNotification);
-
- new Thread() {
- public void run() {
- startDownload();
- };
- }.start();
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- cancelled = true; //中止下載線程
- }
-
- private void startDownload() {
- cancelled = false;
- int rate = 0;
- while (!cancelled && rate < 100) {
- try {
- //模擬下載進度
- Thread.sleep(500);
- rate = rate + 5;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- Message msg = handler.obtainMessage();
- msg.what = 1;
- msg.arg1 = rate;
- handler.sendMessage(msg);
-
- //發送特定action的廣播
- Intent intent = new Intent();
- intent.setAction("android.intent.action.MY_RECEIVER");
- intent.putExtra("progress", rate);
- sendBroadcast(intent);
- }
- if (cancelled) {
- Message msg = handler.obtainMessage();
- msg.what = 0;
- handler.sendMessage(msg);
- }
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- }
可 以看到,咱們在onBind方法裏不在返回自定義的Binder實例了,由於如今的Service和Activitys之間並無綁定關係了,他們是獨立 的;在下載過程當中,咱們會調用sendBroadcast方法,向指定的action發送一個附帶有進度信息的intent,這樣的話,全部註冊過 action爲android.intent.action.MY_RECEIVER的Activity都能收到這條進度消息了。 .net
最後再來看一下FileMgrActivity: 線程
- package com.scott.notification;
-
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ProgressBar;
-
- public class FileMgrActivity extends Activity {
-
- private MyReceiver receiver;
- private ProgressBar progressBar;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.filemgr);
- progressBar = (ProgressBar) findViewById(R.id.progress);
-
- if ("yes".equals(getIntent().getStringExtra("completed"))) {
- progressBar.setProgress(100);
- }
-
- receiver = new MyReceiver();
- IntentFilter filter = new IntentFilter();
- filter.addAction("android.intent.action.MY_RECEIVER");
- //註冊
- registerReceiver(receiver, filter);
- }
-
- public void cancel(View view) {
- Intent intent = new Intent(this, DownloadService.class);
- stopService(intent);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- //不要忘了這一步
- unregisterReceiver(receiver);
- }
-
- /**
- * 廣播接收器
- * @author user
- *
- */
- private class MyReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- Bundle bundle = intent.getExtras();
- int progress = bundle.getInt("progress");
- progressBar.setProgress(progress);
- }
- }
-
- }
我 們發現,FileMgrActivity的模式和MainActivity差很少,也是註冊了相同的廣播接收者,對於DownloadService來講 本身是廣播基站,MainActivity和FileMgrActivity就是聽衆,信號可以同時到達多個聽衆,對於代碼而言,與以前的代碼比較一下, 發現簡潔了許多,顯然這種方式更好一些。 對象
對於咱們上面提到的男女關係,DownloadService就是那個女人,而後兩個男人將本身的 手機號告知了女人,等於註冊了接收器,而後女人將短信羣發給兩個男人。不過在這種狀況下,兩個男人互相都不知道對方的存在,覺得女人深深的愛着本身,等到 發現一切的時候,就是痛苦的時候。相信你們若是遇到這種狀況都會很痛苦吧,至於大家信不信,我反正是信的。哈哈。
其實關於Notification的講解最後兩篇涉及到Notification的很少,主要是圍繞Notification作一些實際的應用示例,但願對於朋友們平時遇到的問題會有所幫助,若是這方面有了新的研究總結,我會再及時更新的,謝謝你們。