最近學習了一下Android裡面的Service的應用,在BindService部分小卡了一下,主要是開始沒有徹底理解為什麼要這麼實現。
BindService和Started Service都是Service,有什麼地方不一樣呢:
1. Started Service中使用StartService()方法來進行方法的調用,調用者和服務之間沒有聯系,即使調用者退出了,服務依然在進行【onCreate()- >onStartCommand()->startService()->onDestroy()】,注意其中沒有onStart(),主要是被onStartCommand()方法給取代了,onStart方法不推薦使用了。
2. BindService中使用bindService()方法來綁定服務,調用者和綁定者綁在一起,調用者一旦退出服務也就終止了【onCreate()->onBind()->onUnbind()->onDestroy()】。
調用者Activity:
MainAcitvity
package com.zys.service;
import com.zys.service.BindService.MyBinder;
import android.R.bool;
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;
public class MainActivity extends Activity {
private Button startBtn;
private Button stopBtn;
private boolean flag;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
flag = false;
//設置
startBtn = (Button)this.findViewById(R.id.startBtn);
stopBtn = (Button)this.findViewById(R.id.stopBtn);
startBtn.setOnClickListener(listener);
stopBtn.setOnClickListener(listener);
}
private OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.startBtn:
bindService();
break;
case R.id.stopBtn:
unBind();
break;
default:
break;
}
}
};
private void bindService(){
Intent intent = new Intent(MainActivity.this,BindService.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
private void unBind(){
if(flag == true){
unbindService(conn);
flag = false;
}
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
MyBinder binder = (MyBinder)service;
BindService bindService = binder.getService();
bindService.MyMethod();
flag = true;
}
};
}