Android -- Service unbinding and aidl

Source: Internet
Author: User

Service is one of the four major components of Android. We previously talked about the Service lifecycle and the example of a non-binding type lifecycle. Here we will share the binding form. The application component (client) can call bindService () to bind to a service. The Android system then calls the onBind () method of the service, which returns an IBinder used to interact with the service. Binding is asynchronous. bindService () returns immediately and does not return IBinder to the client. To receive IBinder, the client must create a ServiceConnection instance and send it to bindService (). ServiceConnection contains a callback method. The system calls this method to pass the IBinder to be returned. To implement ServiceConnection, you must override two callback Methods: The onServiceConnected () system calls this method to send the IBinder returned in the onBind () of the service. OnServiceDisconnected () Android system calls this method when the connection to the service is accidentally lost. For example, when the service crashes or is forced to kill, this method will not be called when the client unbinds. Call bindService () and pass it to the ServiceConnection implementation. When the system calls your onServiceConnected () method, you can use the methods defined by the interface to start calling the service. To disconnect from the service, call unbindService (). Program replication code public class MainActivity extends Activity {private Button btn_start; private Button btn_stop; private Button btn_change; private Button btn_bind; private Button btn_unbind; private MyConn myConn; private IService myBinder; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn_start = (Button) findView ById (R. id. btn_start); btn_stop = (Button) findViewById (R. id. btn_stop); btn_change = (Button) findViewById (R. id. btn_change); btn_bind = (Button) findViewById (R. id. btn_bind); btn_unbind = (Button) findViewById (R. id. btn_unbind); buttonListener bl = new buttonListener (); btn_change.setOnClickListener (bl); btn_start.setOnClickListener (bl); btn_stop.setOnClickListener (bl); listener (bl ); Btn_unbind.setOnClickListener (bl);} class buttonListener implements OnClickListener {@ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_start: Intent intent_start = new Intent (getApplicationContext (), BindService. class); startService (intent_start); break; case R. id. btn_stop: Intent intent_stop = new Intent (getApplicationContext (), BindService. class); stopService (intent_s Top); break; case R. id. btn_change: if (myBinder! = Null) myBinder. doChange (""); break; case R. id. btn_bind: if (myConn = null) {myConn = new MyConn (); Intent intent_bind = new Intent (getApplicationContext (), BindService. class); bindService (intent_bind, myConn, BIND_AUTO_CREATE);} break; case R. id. btn_unbind: Intent intent_unbind = new Intent (getApplicationContext (), BindService. class); if (myConn! = Null & myBinder! = Null) {unbindService (myConn); myConn = null; myBinder = null;} break; default: break ;}}} private class MyConn implements ServiceConnection {@ Override public void onServiceConnected (ComponentName name, IBinder service) {System. out. println ("the agent returned, onServiceConnected"); myBinder = (IService) service ;}@ Override public void onServiceDisconnected (ComponentName name) {System. out. println ("Contact binding Fixed, onServiceDisconnected ") ;}} copy code Service class: Copy code public class BindService extends Service {@ Override public IBinder onBind (Intent intent) {System. out. println ("Service bound successfully, onBind"); // return the custom proxy object return new MyBinder (); // The returned result is the BIND myConn} @ Override public boolean onUnbind (Intent intent) {System. out. println ("Service unbound successfully, onUnbind"); return super. onUnbind (intent);} public class My Binder extends Binder implements IService {// indirect use of the agent to call the changeServiceThing method public void doChange (String what) {changeServiceThing (what) ;}}@ Override public void onCreate () {System. out. println ("Service enabled, onCreate"); super. onCreate () ;}@ Override public void onDestroy () {System. out. println ("Service Disabled, onDestroy"); super. onDestroy ();} public void changeServiceThing (String what) {Toast. makeTe Xt (getApplicationContext (), what + "transformed, changeServiceThing", Toast. LENGTH_LONG ). show () ;}} copy the code IService: public interface IService {public void doChange (String what);} click "enable service" in the result and then "bind service ", it is useless to directly click "Close service" after this execution. You must first "Release the service" and then "Close the service ". If you directly "bind the service", it is useless to click "Close service". You need to click "Unbind service ". Aidl inter-process communication-> If the caller and Service are not in the same process, you need to use the remote Service calling mechanism in android. Android uses AIDL to define inter-process communication interfaces. The syntax of AIDL is similar to that of the java interface. Pay attention to the following points: the AIDL file must be suffixed with. aidl. The data types used in the AIDL interface, except for the basic types, String, List, Map, and CharSequence, all other types need to be imported, even if the two types are in the same package. the element types in List and Map must be supported by AIDL. The interface name must be the same as the file name. When the parameter or return value of a method is a custom type, the Parcelable interface must be implemented for this custom type. All non-java basic type parameters must be marked with in, out, And inout to indicate whether the parameter is an input parameter, an output parameter, or an input/output parameter. The access modifier, static, final, and other modifiers cannot be used before interfaces and methods. For inter-process communication, you need to create an aidl file, IService. aidl: public interface IService {public void doChange (String what);} the interface has a static abstract internal class Stub. The Stub class inherits the Binder class and implements the IRemoteService interface. Copy the public class MainActivity extends Activity {private Intent intent; private IService iService; private ServiceConnection myConn; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} public void bind (View view) {intent = new Intent (); intent. setAction ("com. yydcdut. alipay "); myConn = new MyConn (); boolean flag = bindService (intent, myConn, BIND_AUTO_CREATE); System. out. println ("flag ------>" + flag);} private class MyConn implements ServiceConnection {@ Override public void onServiceConnected (ComponentName, IBinder service) {iService = IService. stub. asInterface (service) ;}@ Override public void onServiceDisconnected (ComponentName name) {}} public void method (View view) {try {iService. callMethodInService ();} catch (RemoteException e) {// catch Block e automatically generated by TODO. printStackTrace ();}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.