Research on Android Service

Source: Internet
Author: User

Research on Android Service
Service is one of the four main components of android. It runs in the background without a user interface. Why do I use the Service to start a new thread to execute time-consuming tasks without directly starting a subthread for processing in the Activity? 1. The Activity will be exited by the user, and the process in which the Activity is located will become a blank process (process without any Activity components). The system may terminate the process preferentially If the memory is required; 2. If the host process is terminated, all the sub-threads in the process will also be terminated, which may cause the sub-threads to fail to be executed; 3. Both methods can process time-consuming tasks in different scenarios. 1. Start a Service in this way. There is no association between the visitor and the service. Even if the visitor exits from the Service, the life cycle is onCreate ()-> onStartCommand () -> onDestroy () defines a subclass that inherits services.

Public class NormalService extends Service {@ Override public IBinder onBind (Intent arg0) {return null ;}@ Override public int onStartCommand (Intent intent, int flags, int startId) {Toast. makeText (this, "started successfully", Toast. LENGTH_SHORT ). show (); Log. d ("NormalService", "started successfully"); // generally, start a new thread to execute the time-consuming operation return super. onStartCommand (intent, flags, startId );}}

 

In AndroidManifest. configure the Service <service android: name = "com. android. servicetest. service. normalService "/> use private void startNormal () {nomalIntent = new Intent (); nomalIntent. setClass (this, NormalService. class); startService (nomalIntent);} 2. Enable Sercice in bind mode. When a visitor is bound to a Service, the Service terminates its lifecycle: onCreate ()-> onBind ()-> onUnbind ()-> onDestroy () defines a subclass that inherits services.
Public class BinderService extends Service {private int count; private MyBinder mBinder; @ Override public IBinder onBind (Intent arg0) {if (mBinder = null) {mBinder = new MyBinder ();} toast. makeText (this, "bound successfully", Toast. LENGTH_SHORT ). show (); Log. d ("BinderService", "bound successfully"); return mBinder ;}@ Override public void onCreate () {super. onCreate (); new Thread (new Runnable () {@ Override public void run () {while (true) {try {Thread. sleep (1000); count ++;} catch (Exception e ){}}}}). start () ;}public class MyBinder extends Binder {public int getCount () {return count ;}}}

 

In the AndroidManifest. xml file, configure the Service <service android: name = "com. android. servicetest. service. BinderService"/>.
private MyBinder mBinder;    private ServiceConnection conn = new ServiceConnection() {    @Override    public void onServiceDisconnected(ComponentName arg0) {    }    @Override    public void onServiceConnected(ComponentName arg0, IBinder binder) {    mBinder = (BinderService.MyBinder) binder;    }};private void bindService() {    bindIntent = new Intent();    bindIntent.setClass(this, BinderService.class);    bindService(bindIntent, conn, Service.BIND_AUTO_CREATE);} 

 

@ Overrideprotected void onDestroy () {super. onDestroy (); unbindService (conn);} The Binder object is equivalent to the internal hook of the Service component and associated with the bound Service component. When other program components are bound to the Service, the Service returns the Binder object to other program components. Other program components can communicate with the Service component in real time through the Binder object. 3. IntentService: IntentService, a Service that processes asynchronous requests, is a subclass of the Service. It adds an additional feature: the queue is used to manage the Intent request. Whenever the client code initiates the IntentService through the Intent request, intentService adds the Intent to the queue and starts a new worker thread to process the Intent in the queue. Therefore, the main thread is not blocked. IntentService processes Intent in the queue in sequence. This thread ensures that only one Intent is processed at the same time. IntentService implementation
Public class IntentServiceTest extends IntentService {public IntentServiceTest () {super ("IntentService") ;}@ Override protected void onHandleIntent (Intent arg0) {Toast. makeText (this, "started successfully", Toast. LENGTH_SHORT ). show (); Log. d ("IntentServiceTest", "started successfully"); // This method can perform time-consuming operations long endTime = System. currentTimeMillis () + 20*1000; while (System. currentTimeMillis () <endTime) {synchronized (this) {try {wait (endTime-System. currentTimeMillis ();} catch (Exception e ){}}}}}

 

In AndroidManifest. configure the Service <service android: name = "com. android. servicetest. service. intentServiceTest "/> use private void startIntentService () {serviceIntent = new Intent (); serviceIntent. setClass (this, IntentServiceTest. class); startService (serviceIntent);} 4. Android applications that call Service (AIDL Service) across processes run in their own processes. Data exchange cannot be directly performed between processes, android provides the AIDL Service for cross-process communication. Creates an AIDL file. The source code of the interface must be. package com. android. servicetest. service; interface IMusic {String getName (); String getYear () ;}after the AIDL interface is defined, the ADT tool automatically generates an IMusic interface in the gen/com/android/servicetest/service/directory. The interface contains an internal class of Stub, in addition to implementing the IMusic interface, this internal class also implements the IBinder interface. This Stub class will be used as the callback class of the remote Service. Defines a Service implementation class
Public class MusicService extends Service {private MusicBinder mBinder; @ Override public IBinder onBind (Intent arg0) {if (mBinder = null) {mBinder = new MusicBinder ();} Toast. makeText (this, "bound successfully", Toast. LENGTH_SHORT ). show (); Log. d ("MusicService", "bound successfully"); return mBinder;} public class MusicBinder extends IMusic. stub {@ Override public String getName () throws RemoteException {return "materia medica" ;}@ Override public String getYear () throws RemoteException {return "2006 ";}}}

 

In the AndroidManifest. xml file, configure the Service <service android: name = "com. android. servicetest. service. MusicService"/> in the activity
Private IMusic musicService; private ServiceConnection = new ServiceConnection () {@ Override public void onServiceDisconnected (ComponentName arg0) {}@ Override public void onServiceConnected (ComponentName arg0, IBinder binder) {// obtain the proxy musicService = IMusic for the object returned by the OnBind method of the remote Service. stub. asInterface (binder) ;}}; private void bindAidlService () {aidlIntent = new Intent (); aidlIntent. setClass (this, MusicService. class); bindService (aidlIntent, connAidl, Service. BIND_AUTO_CREATE);} private void showContent () {String content = ""; try {content = musicService. getYear () + musicService. getName ();} catch (Exception e) {} Toast. makeText (this, content, Toast. LENGTH_SHORT ). show ();}

 

@ Overrideprotected void onDestroy () {super. onDestroy (); unbindService (connAidl);} This method is slightly different from the method used to bind a local Service, but the method used to obtain the Service callback is different: when binding a local Service, you can directly obtain the returned value of the OnBind method. When binding a remote Service, you can obtain the proxy of the object returned by the OnBind method.

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.