bind/unbind service example (android)

匿名 (未验证) 提交于 2019-12-03 02:10:02

问题:

can you give me a simple example of application with background service which uses bind/unbind methods to start and stop it? i was googling for it for an halfhour, but those examples uses startService/stopService methods or are very difficult for me. thank you.

回答1:

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {     @Override     public void onServiceConnected(ComponentName name, IBinder binder) {         Log.d(LOG_TAG, "onServiceConnected");     }      @Override     public void onServiceDisconnected(ComponentName name) {         Log.d(LOG_TAG, "onServiceDisconnected");     } }  public void start() {     // mContext is defined upper in code, I think it is not necessary to explain what is it      mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);     mContext.startService(intent); }  public void stop() {     mContext.stopService(new Intent(mContext, ServiceRemote.class));     mContext.unbindService(mServerConn); }


回答2:

Add these methods to your Activity:

private MyService myServiceBinder; public ServiceConnection myConnection = new ServiceConnection() {      public void onServiceConnected(ComponentName className, IBinder binder) {         myServiceBinder = ((MyService.MyBinder) binder).getService();         Log.d("ServiceConnection","connected");         showServiceData();     }      public void onServiceDisconnected(ComponentName className) {         Log.d("ServiceConnection","disconnected");         myService = null;     } };  public Handler myHandler = new Handler() {     public void handleMessage(Message message) {         Bundle data = message.getData();     } };  public void doBindService() {     Intent intent = null;     intent = new Intent(this, BTService.class);     // Create a new Messenger for the communication back     // From the Service to the Activity     Messenger messenger = new Messenger(myHandler);     intent.putExtra("MESSENGER", messenger);      bindService(intent, myConnection, Context.BIND_AUTO_CREATE); }

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override protected void onResume() {      Log.d("activity", "onResume");     if (myService == null) {         doBindService();     }     super.onResume(); }  @Override protected void onPause() {     //FIXME put back      Log.d("activity", "onPause");     if (myService != null) {         unbindService(myConnection);         myService = null;     }     super.onPause(); }

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private         
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!