activity中怎么获取service对象

avatar
作者
筋斗云
阅读量:1

在Activity中获取Service对象可以通过以下步骤:

  1. 在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);     } } 
  1. 在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对象并调用其方法。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!