Android note. Service integrated instance (1), android. service

Source: Internet
Author: User

Android note. Service integrated instance (1), android. service
Integrated instance 1: access the local ServiceA) start and stop the Service through startService () of Context;B) bind and unbind using the bindService () method of Context;The local Activity obtains and communicates with the service to obtain service-related data.
1. Source Code(1) src/MainActivity. java: Application master AcitvityFunction: Get the interface component, register the event listener (internal class form) for the relevant component, start the specified Service, and communicate with the Service. Core steps: a) instantiate two Intent objects (Intent service ), specifies the local Service to start. B) for non-binding Service:> call Context. startService (Intent service) starts a non-binding Service;> call Context. stopService (Intent intent) disables the Service. For the binding Service:> call Context. bindService (Intent service, ServiceConnection conn, int flags) Start the binding Service;> call unbindService (ServiceConnection conn) to unbind from Servcie and disable the Service;> Create a ServcieConnection object to listen to the connection between the visitor and the Service (1) connection successful: Call back the onServiceConnected (ComponentName, IBinder service) method of the ServiceConnection object (2) Connection Failed: call back the onServiceDisconnected (ComponentName name) method. The onServiceConnected method is used to obtain the IBinder object returned by the onBind () method of the Service. Through this object, we can implement communication with the Service.

<Span style = "font-family: Times New Roman; font-size: 18px;"> package com. example. servicetest1; import android. app. activity; import android. app. service; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; import android. OS. bundle; import android. OS. IBinder; import android. view. view; import android. view. view. onClickListener; import android. widget. button; I Mport android. widget. toast; public class MainActivity extends Activity {private Button startService; private Button stopService; private Button bindService; private Button unbindService; private Button getData; private MyBindService. myIBinder binder; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); //. get interface component startSer Vice = (Button) findViewById (R. id. start); stopService = (Button) findViewById (R. id. stop); bindService = (Button) findViewById (R. id. bind); unbindService = (Button) findViewById (R. id. unbind); getData = (Button) findViewById (R. id. get); // B. register the same Listener MyEvent Listener = new MyEvent () for the component; // instantiate an event Listener startService. setOnClickListener (Listener); // register the Listener object stopService for the component. setOnClickListener (Listener); bindService. SetOnClickListener (Listener); unbindService. setOnClickListener (Listener); getData. setOnClickListener (Listener);}/* 1. internal class of event processing * obtains the view component (v) and determines the component ID to respond to the specific component */public class MyEvent implements OnClickListener {//. set "Intent" Intent intent1 = new Intent ("com. jiangdongguo. myService "); Intent intent2 = new Intent (" com. jiangdongguo. myBindService "); // B. start the specified service public void onClick (View v) {s Witch (v. getId () {// (1) Start common Service case R. id. start: startService (intent1); // start the break of the Service specified by "intent"; // (2) Disable normal Service case R. id. stop: stopService (intent1); // close the break of the Service specified by "intent"; // (3) Start and bind Service case R. id. bind: bindService (intent2, conn, Service. BIND_AUTO_CREATE); break; // (4) unbind from Service case R. id. unbind: unbindService (conn); break; // (5) obtain data from the service case R. id. get: Toast. makeTe Xt (MainActivity. this, "the data read from the Service is: count =" + Integer. toString (binder. getCount (), Toast. LENGTH_SHORT ). show (); break; default: break; }}/ * 2. servcieConnection anonymous internal class: Create a ServcieConnection object * the object of this internal class is used to listen on the connection between the visitor and the Service * (1) the connection is successful: call back the onServiceConnected (ComponentName name, IBinder service) method of the ServiceConnection object * (2) connection failure: Call back the onServiceDisconnected (ComponentName name) Method */private ServiceConnection co Nn = new ServiceConnection () {//. connection successful: This method is used to obtain the IBinder object returned by the Service and communicate with the Service. public void onServiceConnected (ComponentName, IBinder service) {System. out. println ("--- MainActivity's onServiceConnected invoked! --- "); Binder = (MyBindService. myIBinder) service; // get the IBinder object returned by the Service} // B. failed to connect to the service: public void onServiceDisconnected (ComponentName name) {System. out. println ("--- MainActivity's onServiceDisconnected invoked! --- "); Toast. makeText (MainActivity. this," failed to bind to Service. Please try again. ", Toast. LENGTH_SHORT). show () ;}}</span>
(2) src/MyService. java: non-binding ServiceFunction: inherits the sub-class of the Service, so that when a visitor calls the related Context. core steps of method development for Xxxx () method callback: a) rewrite Context. startService (Intent service) method for starting Service callback> onCreate (): initialization is completed or the related business logic code> onStartCommand (Intent intent, int flags, int startId ): complete related business logic code B) rewrite Context. stopService (Intent intent) method for disabling Service callback> onDestory (): Disable Service. Note: The onBind method is an abstract method and must be implemented in code. However, the visitor and the Service are not bound and cannot communicate with each other. Therefore, you only need to return null if you do not need to implement this method.
<Span style = "font-family: Times New Roman; font-size: 18px;"> package com. example. servicetest1; import android. app. service; import android. content. intent; import android. OS. IBinder; public class MyService extends Service {/* 1. onBind Method * service is used to return an IBinder object to the client for convenient communication * If the visitor uses Context. startService starts the Service and returns NULL */@ Override public IBinder onBind (Intent arg0) {System. out. println ("--- MyService's onBind I Nvoked! --- "); Return null;}/* 2. onCreate Method * when the Service is started, this method is automatically called to initialize **/public void onCreate () {System. out. println ("--- MyService's onCreate invoked! --- "); Super. onCreate ();}/* 3. onStartCommand Method * this method is called back every time a visitor calls the startService method to start the Service */public int onStartCommand (Intent intent, int flags, int startId) {System. out. println ("--- MyService's onStartCommand invoked! --- "); Return super. onStartCommand (intent, flags, startId);}/* 4. onDestroy Method * When a visitor calls Context. after the stopService method, call this method to disable the Service **/public void onDestroy () {System. out. println ("--- MyService's onDestory invoked! --- "); Super. onDestroy () ;}</span>
(3) src/MyBindService. java: Binding ServiceFunction: inherits the sub-class of the Service, so that when a visitor calls the related Context. core steps of method development for Xxxx () method callback: a) rewrite Context. bindService (Intent service, ServiceConnection conn, int flags) method for starting Service callback> onCreate (): Completing initialization or related business logic code> IBinder onBind (Intent arg0 ): returns an IBinder object to visitor B) to implement an internal class. This class inherits from the Binder class and provides related methods so that visitors can call this class member method through the obtained IBinder object, this allows communication between visitors and Service services. For example, public class MyIBinder extends Binder {/*..... member methods or variables ...... */} c) rewrite Context. unbindService (ServiceConnection conn) method for disabling Service callback> onUnbind (Intent intent): unbinds a visitor to the Service> onDestory (): disables the Service. Note: The onBind method is an abstract method, must be implemented in the code. The purpose of binding a client to a Service is to achieve communication between the two, and their communication media is an IBinder object, visitors can use the IBinder object to call the member methods in the IBinder internal class of the Service subclass to access data of the Service.
<Span style = "font-family: Times New Roman; font-size: 18px;"> package com. example. servicetest1; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. IBinder; public class MyBindService extends Service {private int count = 0; private boolean threadFlag = true; // The end thread flag MyIBinder bind = new MyIBinder (); // instantiate a Binder object, used to be returned to the visitor by the onBind method/* 0. binder subclass * its objects are used to communicate with visitors and access The user obtains data in the Service by calling the method in the IBinder subclass */public class MyIBinder extends Binder {// custom member method, which is used to return the public int getCount () data in the Service () {return count ;}}/* 1. onBind Method * service is used to return an IBinder object to the client for convenient communication * If the visitor uses Context. startService starts the Service and returns NULL */@ Override public IBinder onBind (Intent arg0) {System. out. println ("--- MyService's onBind invoked! --- "); Return bind;}/* 2. onCreate Method * when the Service is started, this method is automatically called to initialize **/public void onCreate () {System. out. println ("--- MyService's onCreate invoked! --- "); // Create a Thread to update the value of count at a certain interval. new Thread () {public void run () {while (threadFlag) // The default value is true {try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace () ;}count ++ ;}}}. start (); super. onCreate ();}/* 3. onStartCommand Method * this method is called back every time a visitor calls the startService method to start the Service */public int onStartCommand (Intent intent, int flags, int startId) {System. out. println ("--- MyService's onStartCo Mmand invoked! --- "); Return super. onStartCommand (intent, flags, startId);}/* 4. onDestroy Method * When a visitor calls Context. after the stopService method, call this method to disable the Service **/public void onDestroy () {System. out. println ("--- MyService's onDestory invoked! --- "); ThreadFlag = false; super. onDestroy ();}/* 5. onUnbind Method * When a visitor calls Context. unBind () method, call this method to unBind from Service */public boolean onUnbind (Intent intent) {System. out. println ("--- MyService's onUnbind invoked! --- "); Return super. onUnbind (intent) ;}</span>
Note: In the binding Service, we mainly use threads to process time-consuming tasks. This involves a problem, that is, when we exit the application, the sub-thread is still running, and it is not over, so that the thread will become an orphan thread, it is easy to be killed by the system, resulting in task failure. To solve this problem, we set a condition flag for the sub-thread. When the program calls onDestory to end the service, the sub-thread ends. 2. effect demonstration(1) Non-Binding
(2) binding (3) interface effect

3. Source Code Analysis(1) The onCreate () method is called back every time the Service is created, and the onStartCommand () method is called back every time the Service is started, when an existing Service component is started multiple times, the onCreate () method is no longer called back, but the onStartCommand () method is called back every time it is started. (2) binding Service Execution Process: Click the event Method locate to find the corresponding Service class based on Intent, and initialize this class of producer to call the onCreate () method consumer calls the onBind () method consumer of this class to call the onServiceConnected () method. Click the bind Service button multiple times, and the binding method is not repeated. Once unbound, The onunBind () method is called and then destroyed automatically.
Note: a) directly stopping a Service without starting the Service does not work, but unbinding a Service without binding it causes an error in the program and forcibly exits. B) if the Service is bound, this Service will not be stopped, that is, clicking the stop button does not work. When you click the unbind Service button, it unbinds the Service and then destroys it directly. c) If you do not click STOP Service before unbinding, only unbind and not destroy.

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.