在Activity中獲取Service對象可以通過以下步驟:
bindService()
方法綁定Service。在onServiceConnected()
方法中獲取Service對象。public class MyActivity extends Activity {
private MyService myService;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder binder = (MyService.MyBinder) service;
myService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
};
@Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, MyService.class);
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
unbindService(serviceConnection);
}
}
public class MyService extends Service {
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
通過這樣的方式,可以在Activity中獲取到Service對象并調用其方法。