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

Android Activity 與 Service 資料交互實作

編輯:關於 Android 程式設計

在 Android 中,Activity 負責與使用者互動,Service 則適合執行背景任務。當 Service 執行較長時間的操作時,可以透過 Binder 與回呼介面,把進度或結果傳回 Activity。

Service 的兩種啟動方式:

  • startService:適合只需要執行一次或持續背景執行的任務。
  • bindService:適合 Activity 需要與 Service 建立連接並取得資料的情境。

兩者的生命週期如下:

Service 端設計

這個範例建立一個模擬下載的 Service,透過自訂 Binder 提供 Service 實例,並用回呼介面通知 Activity 下載進度。

public class MsgService extends Service {
    public static final int MAX_PROGRESS = 100;
    private int progress = 0;
    private OnProgressListener onProgressListener;

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

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

    public void setOnProgressListener(OnProgressListener listener) {
        this.onProgressListener = listener;
    }

    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 MyBinder();
    }
}

Activity 端綁定 Service

Activity 透過 bindService 取得 Service,並註冊進度回呼,更新 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);

        mProgressBar = findViewById(R.id.progressBar);

        Intent intent = new Intent(this, MsgService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

        findViewById(R.id.btnExec).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgService.startDownLoad();
            }
        });
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MsgService.MyBinder binder = (MsgService.MyBinder) service;
            msgService = binder.getService();

            msgService.setOnProgressListener(new MsgService.OnProgressListener() {
                @Override
                public void onProgress(int progress) {
                    mProgressBar.setProgress(progress);
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

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

這個範例展示了同進程中 Activity 與 Service 的資料交互方式。若需要跨進程,則要改用 AIDL 或 Messenger。

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