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

Android Service 與 Activity 通訊的兩種經典做法

編輯:關於 Android 程式設計

在 Android 中,Activity 主要負責前台頁面的呈現,Service 則負責需要長期運行的任務。實務開發時,兩者之間的通訊幾乎無可避免。我們通常在 Activity 中啟動後台 Service,透過 Intent 把資料傳進去;但當 Service 執行完某些操作、想要回過頭來更新 UI 時,該怎麼做?以下介紹兩種常見方案。

一、透過 Binder 物件

當 Activity 呼叫 bindService(Intent service, ServiceConnection conn, int flags) 後,就能取得 Service 的物件參照,進而直接呼叫 Service 中的方法。以下用一個模擬下載的小例子來說明。

先建立工程 Communication,並新增一個 Service 類別:

package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MsgService extends Service {

    /** 進度條最大值 */
    public static final int MAX_PROGRESS = 100;

    /** 進度條的目前進度 */
    private int progress = 0;

    /** 對外提供的 get() 方法,供 Activity 呼叫 */
    public int getProgress() {
        return progress;
    }

    /** 模擬下載任務,每秒更新一次 */
    public void startDownLoad() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progress < MAX_PROGRESS) {
                    progress += 5;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /** 回傳一個 Binder 物件 */
    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }

    public class MsgBinder extends Binder {
        /** 取得目前的 Service 實例 */
        public MsgService getService() {
            return MsgService.this;
        }
    }
}

這段程式碼相當基礎,註解也寫得完整。startDownLoad() 用來模擬下載,每秒推進一次進度,但这一切都發生在背景,使用者看不到。因此我們需要 Activity 來把進度呈現出來。

Intent intent = new Intent("com.example.communication.MSG_ACTION");
bindService(intent, conn, Context.BIND_AUTO_CREATE);

透過這段程式碼就在 Activity 中綁定了 Service。這裡需要一個 ServiceConnection 物件,它是個介面,本例使用匿名內部類實作:

ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 取得 MsgService 物件
        msgService = ((MsgService.MsgBinder) service).getService();
    }
};

在 onServiceConnected(ComponentName name, IBinder service) 這個回呼中,我們拿到了 MsgService 內部的 Binder 物件,再呼叫 getService() 就能取得 MsgService 實例,之後便可以呼叫它公開的方法。Activity 的完整程式碼如下:

package com.example.communication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

    private MsgService msgService;
    private int progress = 0;
    private ProgressBar mProgressBar;

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

        // 綁定 Service
        Intent intent = new Intent("com.example.communication.MSG_ACTION");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        Button mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 開始下載
                msgService.startDownLoad();
                // 監聽進度
                listenProgress();
            }
        });
    }

    /** 監聽進度,每秒呼叫一次 MsgService 的 getProgress() 並更新 UI */
    public void listenProgress() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progress < MsgService.MAX_PROGRESS) {
                    progress = msgService.getProgress();
                    mProgressBar.setProgress(progress);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            msgService = ((MsgService.MsgBinder) service).getService();
        }
    };

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }
}

這樣就完成了 Service 更新 UI 的效果。但仔細想想會發現一个问题:我們每次都得主動呼叫 getProgress() 取得進度,還要每隔一秒再呼叫一次,顯得相當被動。有沒有可能讓 Service 在進度變化時主動通知 Activity?答案是肯定的,利用回呼介面即可。

先定義一個回呼介面:

public interface OnProgressListener {
    void onProgress(int progress);
}

MsgService 只需稍作調整:

package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MsgService extends Service {

    /** 進度條最大值 */
    public static final int MAX_PROGRESS = 100;

    /** 進度條的目前進度 */
    private int progress = 0;

    /** 更新進度的回呼介面 */
    private OnProgressListener onProgressListener;

    /** 註冊回呼介面,供外部呼叫 */
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

    public int getProgress() {
        return progress;
    }

    /** 模擬下載任務,每秒更新一次 */
    public void startDownLoad() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progress < MAX_PROGRESS) {
                    progress += 5;
                    // 進度改變時通知呼叫方
                    if (onProgressListener != null) {
                        onProgressListener.onProgress(progress);
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }

    public class MsgBinder extends Binder {
        public MsgService getService() {
            return MsgService.this;
        }
    }
}

Activity 端程式碼:

package com.example.communication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

    private MsgService msgService;
    private ProgressBar mProgressBar;

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

        // 綁定 Service
        Intent intent = new Intent("com.example.communication.MSG_ACTION");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        Button mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                msgService.startDownLoad();
            }
        });
    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            msgService = ((MsgService.MsgBinder) service).getService();
            // 註冊回呼介面,接收下載進度變化
            msgService.setOnProgressListener(new OnProgressListener() {
                @Override
                public void onProgress(int progress) {
                    mProgressBar.setProgress(progress);
                }
            });
        }
    };

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }
}

相較之下,回呼介面顯然方便許多:進度一有變化,Service 主動通知 Activity,Activity 再更新 UI 即可。

二、透過廣播

另一種做法是:進度改變時送出廣播,Activity 端註冊廣播接收器,收到後更新 ProgressBar。

package com.example.communication;

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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

    private ProgressBar mProgressBar;
    private Intent mIntent;
    private MsgReceiver msgReceiver;

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

        // 動態註冊廣播接收器
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.communication.RECEIVER");
        registerReceiver(msgReceiver, intentFilter);

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        Button mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 啟動服務
                mIntent = new Intent("com.example.communication.MSG_ACTION");
                startService(mIntent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        // 停止服務
        stopService(mIntent);
        // 取消註冊廣播
        unregisterReceiver(msgReceiver);
        super.onDestroy();
    }

    /** 廣播接收器 */
    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 取得進度並更新 UI
            int progress = intent.getIntExtra("progress", 0);
            mProgressBar.setProgress(progress);
        }
    }
}
package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MsgService extends Service {

    /** 進度條最大值 */
    public static final int MAX_PROGRESS = 100;

    /** 進度條的目前進度 */
    private int progress = 0;

    private Intent intent = new Intent("com.example.communication.RECEIVER");

    /** 模擬下載任務,每秒更新一次 */
    public void startDownLoad() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progress < MAX_PROGRESS) {
                    progress += 5;
                    // 送出 action 為 com.example.communication.RECEIVER 的廣播
                    intent.putExtra("progress", progress);
                    sendBroadcast(intent);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startDownLoad();
        return super.onStartCommand(intent, flags, startId);
    }

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

總結

  • Activity 呼叫 bindService(Intent service, ServiceConnection conn, int flags) 取得 Service 的參照後,可直接呼叫 Service 的方法;若要讓 Service 主動通知 Activity,搭配回呼介面即可。
  • Service 向 Activity 傳遞訊息時,可以使用廣播,但 Activity 必須註冊對應的接收器。若 Service 需要向多個 Activity 廣播同一則訊息,這種方式會更合適。

以上就是本文的全部內容,希望對大家的學習有所幫助。

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