編輯:關於 Android 程式設計
在 Android 中,Activity 負責與使用者互動,Service 則適合執行背景任務。當 Service 執行較長時間的操作時,可以透過 Binder 與回呼介面,把進度或結果傳回 Activity。
Service 的兩種啟動方式:
startService:適合只需要執行一次或持續背景執行的任務。bindService:適合 Activity 需要與 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 透過 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。
Activity 生命週期與啟動模式完整解析
Activity 生命週期與啟動模式解析 Activity 是 Android 中最常見的四大元件之一,理解其生命週期與啟動模式,是掌握頁面跳轉、狀態保存與任務棧管理的基
Android 高仿小米時鐘:Camera 與 Matrix 實現 3D 效果
這個範例會製作一個接近小米風格的時鐘,除了自定義 View,也會用到 Camera 與 Matrix 呈現 3D 觸摸效果。 繪製順序 建議由外到內、由深到淺繪製。先處
Android 學習教程(5):分類側滑選單的實作
本文示範一個帶分類切換效果的側滑選單,基於 DrawerLayout 搭配 Circular Reveal 動畫,切換分類時以指點位置為圓心做圓形展開轉場。 class
談談 Android 中 Context 的靈活使用技巧
大家好,今天想和大家聊聊 Android 裡 Context 的幾種用法。以前常有朋友在群組裡問我:如果在某個工具類的方法裡,或者在 View 當中需要使用 Contex