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