在活動中控制服務的實現。
在服務裏實現下載功能
第一步:在服務類中添加如下代碼:
private DownloadBinder mBinder = new DownloadBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class DownloadBinder extends Binder{
public void startDownload(String url){
//實現開始下載邏輯
}
public void pauseDownload(){
//實現暫停下載邏輯
}
public void cancelDownload(){
//實現取消下載邏輯
}
}
第二步:在活動中添加代碼
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
//活動與服務綁定成功時調用
public void onServiceConnected(ComponentName componentName, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
@Override
//活動與服務解除綁定時調用
public void onServiceDisconnected(ComponentName componentName) {
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DownloadService.class);
startService(intent);//啓動服務
bindService(intent, connection, BIND_AUTO_CREATE);//綁定服務
}
@Override
//活動結束後解除綁定
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}