Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發實戰(十):應用程式間的四種溝通方式——Handler、通知欄、廣播與 Intent

編輯:關於 Android 開發

Android 在程式之間通訊這件事上,介面設計得相當豐富。這一節把最常打交道的四種溝通方式一次講清楚:各自解決什麼問題、怎麼實作、又有哪些容易忽略的細節。

一、用 Handler 傳遞消息

你可以把 Handler 想成主線程(UI 線程)的一個代理人:背景執行緒把資料交給它,由它排進佇列、在主線程上執行,據此更新介面與邏輯。

為什麼非要繞這一層?因為 Android 的 UI 元件不是執行緒安全的,只能在建立它的那條執行緒上操作。而且主線程一旦被阻塞超過五秒,系統就會跳出 ANR 對話框,讓使用者選擇強制關閉——所以耗時工作必須丟到背景,結果再透過 Handler 送回主線程呈現。

下面的例子:按下按鈕後啟動執行緒,每過一秒透過 Handler 送一則消息更新畫面上的計時文字,數到 10 之後送出「完成」並結束執行緒。

public class HandlerActivity extends Activity implements Runnable {

    /** 更新時間 */
    public final static int UPDATE_TIME = 0;
    /** 更新完成 */
    public final static int UPDATE_COMPLETED = 1;

    /** 記錄顯示時間,超過 10 秒結束執行緒 */
    private int mShowNumber = 0;
    private Button mButton = null;
    private TextView mTextView = null;
    private Thread mThread = null;
    /** 執行緒是否繼續 */
    private boolean mRunning = false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            // 以 key 取出值
            String number = bundle.getString("number");
            // msg.what 是消息編號,用來分流
            switch (msg.what) {
                case UPDATE_TIME:
                    mTextView.setText("正在更新時間" + number);
                    break;
                case UPDATE_COMPLETED:
                    mTextView.setText("更新完畢");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.handler);
        mButton = (Button) findViewById(R.id.button0);
        mTextView = (TextView) findViewById(R.id.textView0);
        mThread = new Thread(this);

        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 按下按鈕後啟動計時
                mRunning = true;
                mThread.start();
            }
        });
        mTextView.setText("點擊按鈕開始更新時間");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void run() {
        while (mRunning) {
            try {
                mShowNumber++;
                // 把要傳的資料放進 Bundle
                Bundle bandle = new Bundle();
                bandle.putString("number", String.valueOf(mShowNumber));

                Message msg = new Message();
                if (mShowNumber <= 10) {
                    msg.what = UPDATE_TIME;
                } else {
                    mRunning = false;
                    msg.what = UPDATE_COMPLETED;
                }
                msg.setData(bandle);
                handler.sendMessage(msg);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

這裡的設計要點:資料裝在 Bundle 裡隨 Message 一起送,msg.what 則當作分流用的編號,接收端靠它決定要更新哪一段 UI。另外提醒一個實務問題——匿名內部類別會隱式持有 Activity 的參考,若執行緒還在跑而 Activity 已經關閉,就會造成記憶體洩漏。正式專案裡應在 onDestroy() 中把 mRunning 設為 false,並視情況呼叫 handler.removeCallbacksAndMessages(null)。

二、Notification 通知欄

通知欄會在螢幕上方提示訊息,但不會打斷使用者正在閱讀的內容,除非他自己把通知欄拉下來。這個特性在「不該打斷」的場合特別有用——使用者正在看一段很重要的資訊,這時直接幫他跳轉到另一個 Activity 就非常突兀。遇到可能干擾當下操作的時機,優先考慮通知欄。

       螢幕上方為弹出的通知欄

拉下通知欄之後,就會看到完整的訊息內容。

public class NotificationActivity extends Activity {

    NotificationManager mManager = null;
    Notification notification = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.notification);

        // 取得通知管理器,負責發送與清除通知
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // 建立 Notification:參數依序為圖示、標題、時間
        notification = new Notification(R.drawable.jay, "Android 專業開發群", System.currentTimeMillis());

        // 點擊後自動消失
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        // 點擊後要跳轉的 Activity
        Intent intent = new Intent(this, MyShowActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

        // 用 Bundle 帶點資料過去
        Bundle bundle = new Bundle();
        bundle.putString("name", "從 Notification 跳轉過來的");
        intent.putExtras(bundle);

        // 通知欄中顯示的內容
        PendingIntent contentIntent = PendingIntent.getActivity(this, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(this, "Android 專業開發群", "QQ 群號 164257885", contentIntent);

        Button button0 = (Button) findViewById(R.id.button0);
        button0.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 發出通知
                mManager.notify(0, notification);
            }
        });

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 清除所有通知
                mManager.cancelAll();
            }
        });

        super.onCreate(savedInstanceState);
    }
}

PendingIntent 是這段程式裡最需要理解的角色。它代表「一段未來才會被執行的 Intent」,交給系統保管,等到使用者真的點了通知,系統才代你執行。因此它需要一個 requestCode(此處用字串資源當識別)與一組 flags。

要補充的是,setLatestEventInfo() 屬於早期寫法,在後續版本已被 Notification.Builder 取代。新專案請直接用 Builder 串起圖示、標題、內容與 PendingIntent,程式碼會乾淨許多,相容性也更好。

三、廣播的發送與接收

如果要在兩個彼此毫無關聯的程式之間通信,廣播是最直接的機制:A 發出一則廣播,B 收到後做點事情,通訊就完成了。它天生支援一對多,發送方完全不需要知道有誰在聽。

發送端只要呼叫 sendBroadcast() 並傳入 Intent:

public class BroadcastActivity extends Activity {

    Button mButton0 = null;
    Button mButton1 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.broadcast);

        mButton0 = (Button) findViewById(R.id.button0);
        mButton0.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(MyService.SEND_OK_MESSAGE);
                intent.putExtra("name", "您發送了 OK 這條廣播哦");
                sendBroadcast(intent);
            }
        });

        mButton1 = (Button) findViewById(R.id.button1);
        mButton1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(MyService.SEND_CANCLE_MESSAGE);
                intent.putExtra("name", "您發送了 Cancle 這條廣播哦");
                sendBroadcast(intent);
            }
        });

        // 啟動 Service
        Intent i = new Intent(this, MyService.class);
        startService(i);
        super.onCreate(savedInstanceState);
    }
}

接收端這裡開一個 Service,在裡面用 BroadcastReceiver 收,並且在 AndroidManifest.xml 中過濾只接收需要的 action:

<service android:name=".MyService">
    <intent-filter>
        <action android:name="cn.m15.xys.MyService"></action>
    </intent-filter>
    <intent-filter>
        <action android:name="send.ok.message" />
        <action android:name="send.cancle.message" />
    </intent-filter>
</service>
public class MyService extends Service {

    public final static String SEND_OK_MESSAGE = "send.ok.message";
    public final static String SEND_CANCLE_MESSAGE = "send.cancle.message";

    private BroadcastReceiver myBroadCast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SEND_OK_MESSAGE)) {
                Toast.makeText(context, "接收到了一條廣播為" + SEND_OK_MESSAGE, Toast.LENGTH_LONG).show();
            } else if (action.equals(SEND_CANCLE_MESSAGE)) {
                Toast.makeText(context, "接收到了一條廣播為" + SEND_CANCLE_MESSAGE, Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // 在這裡註冊需要的兩個廣播
        IntentFilter myFilter = new IntentFilter();
        myFilter.addAction(SEND_OK_MESSAGE);
        myFilter.addAction(SEND_CANCLE_MESSAGE);
        this.registerReceiver(myBroadCast, myFilter);
        super.onStart(intent, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

這裡有個很實際的陷阱:Service 沒起來,廣播就收不到。上例的 Service 是在打開 Activity 時才啟動的,一旦使用者關機重開,Service 就不在執行,任何訊息都收不到,除非他再進一次 Activity。

解法是攔住系統的開機廣播。android.intent.action.BOOT_COMPLETED 只在開機完成時發出一次,收到它就代表手機剛開機,正好可以把 Service 拉起來。

<receiver android:name=".MyBootReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
public class MyBootReceiver extends BroadcastReceiver {
    /** 開機廣播 */
    static final String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {
        // 若是開機廣播,就啟動 Service
        if (intent.getAction().equals(BOOT_COMPLETED)) {
            Intent i = new Intent(context, MyService.class);
            context.startService(i);
        }
    }
}

順帶一提,動態註冊的接收器記得在不需要時呼叫 unregisterReceiver(),否則同樣會洩漏。

四、Activity 之間的跳轉與傳值

一個應用不可能只有一個畫面,畫面之間必然存在跳轉關係。做法一樣是 Intent 加 startActivity(),而且跳轉時可以帶資料過去。

讀完下面的程式碼你可能會想:Intent 和 Bundle 傳值的方式幾乎一樣,為什麼要分兩種?差別在組織方式:Intent 是把零散的資料一個個掛上去,Bundle 則是先把零散資料收進一個容器,再整包交出去。

舉例說明。有三個 Activity:A、B、C,要把 A 的資料一路傳到 C。用 Intent 逐項傳,B 得先把每個值都取出來,再一個個掛上去傳給 C,很囉嗦;用 Bundle 的話,B 直接把整包轉交給 C,不必關心裡面裝了什麼,由 C 自己解包解析。層數越多,這個差異越明顯。

發送端:

// Activity 之間傳值
Button botton3 = (Button) findViewById(R.id.button3);
botton3.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        Intent intent = new Intent(mContext, ShowActivity.class);

        // 寫法一:用 intent.putExtra() 直接傳
        intent.putExtra("name", "雨松 MOMO");
        intent.putExtra("age", 25);
        intent.putExtra("boy", true);

        // 寫法二:先放進 Bundle,再把整包塞給 intent
        Bundle bundle = new Bundle();
        bundle.putString("b_name", "小可愛");
        bundle.putInt("b_age", 23);
        bundle.putBoolean("b_boy", false);
        intent.putExtras(bundle);

        // 開啟新 Activity
        startActivity(intent);
    }
});

接收端:

public class ShowActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.my);

        Intent intent = getIntent();

        String name = intent.getStringExtra("name");
        // 第二個參數是預設值:拿不到時就用它
        int age = intent.getIntExtra("age", 0);
        boolean isboy = intent.getBooleanExtra("boy", false);

        TextView textView0 = (TextView) findViewById(R.id.text0);
        textView0.setText("姓名 " + name + " 年齡 " + age + " 男孩? " + isboy);

        Bundle bundle = intent.getExtras();
        name = bundle.getString("b_name");
        age = bundle.getInt("b_age", 0);
        isboy = bundle.getBoolean("b_boy", false);

        TextView textView1 = (TextView) findViewById(R.id.text1);
        textView1.setText("姓名 " + name + " 年齡 " + age + " 男孩? " + isboy);

        super.onCreate(savedInstanceState);
    }
}

接收端這裡有個習慣值得養成:getIntExtra()、getBooleanExtra() 這些取值方法都帶一個預設值參數,一旦對方沒傳,你不至於拿到 null 而崩潰。跨 Activity 傳值本質上是一份「口頭契約」,多一層防禦總沒錯。

源碼下載地址:https://vdisk.weibo.com/s/aa3fI

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved