阅读量:1
在Activity中获取Service对象可以通过以下步骤:
- 在Activity中使用
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); } }
- 在Service中创建一个Binder类用于返回Service对象。
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对象并调用其方法。