Android Development Research on service

Source: Internet
Author: User

Two years of learning about the technology of the service during Android development

I've never had time to sort this out. Now there's time for a detailed, in-depth code to understand the service.


I. Service and activity

Android development is inseparable from activity activity equivalent to win window

But generally there is only one reality in front of the other activity is either pressed to the back of the stack or manually destroyed.

While a service is capable of starting multiple such service is quite a parallel state

And the service can remain relatively independent of activity.

In other words, you can start the service in Activitya

Send a message to the service in Activityb

Finally, close the service in ACTIVITYC

These few activity turns reality in front


Two. Service and Threads

It's easy to understand the service if you understand threading.

Activity Service is performed in the main thread, but the activity object is only one display in the front end

The service does not appear in the front end and can generate multiple objects

The data stored in the service is not destroyed as the data in the activity is destroyed with the activity

Alternatively, you can open a new thread as a background processing thread

Completely independent of activity only handling messages sent by activity


Three. Code


In manifest

Register 2 Activity A service

<activity            android:name= "com.example.codetest_1.MainActivity"            android:label= "@string/app_name" >            <intent-filter>                <action android:name= "Android.intent.action.MAIN"/>                <category Android:name= "Android.intent.category.LAUNCHER"/>            </intent-filter>        </activity>                 < Activity            android:name= "com.example.codetest_1.SecActivity" >           </activity>        <service Android:enabled= "true" android:name= "Com.services.sev.PlayService"/>
Layout

Activity_main first activity gives three buttons start service end service and next interface

Activity_sec The second activity also gives three buttons to exit the interface to send messages 2 and end service


mainactivity button Handling

public void OnClick (View arg0) {//TODO auto-generated method stubs        switch (Arg0.getid ()) {case        (r.id.button_on):        //Start Service        this.startservice (New Intent (this, playservice.class));            break;        Case (R.id.button_off): {        //stop Service             this.stopservice (New Intent (This,playservice.class));        }            break;        Case (R.id.button_next): {        //Open another activity        Intent Intent = new Intent ();    Intent.setclass (Mainactivity.this, secactivity.class);    StartActivity (intent);                }            break;         Default: Break             ;                }}


secactivity button Handling

public void OnClick (View arg0) {        switch (Arg0.getid ()) {case        (R.ID.BUTTON_ESC):        //Exit activity        Finish ( );            break;        Case (R.id.button_off): {        //Close service        this.stopservice (new Intent (This,playservice.class));        }            break;        Case (R.ID.BUTTON_STEP2): {        //Send message to service        Intent Intent = new Intent (this, playservice.class);        Bundle bundle = new bundle ();          Bundle.putint ("Op", 2);          Intent.putextras (bundle);              This.startservice (intent);       }        break;        Default: Break        ;        }}


Playservice Complete code

public class Playservice extends Service {private handlerthread mhandlerthread;private Handler Mplayhandler;    Class Playhandler extends handler{public Playhandler () {} public Playhandler (Looper LP) {super (LP); } @Override public void Handlemessage (Message msg) {//TODO auto-generated method stub super.handlemes        Sage (msg);    Data received for threading//Note here is not on the main thread but on a separate thread System.out.println ("Playhandler handlemessage");    System.out.println ("Playhandler thread ID:" +thread.currentthread (). GetId ()); }} @Override public IBinder onbind (Intent Intent) {//TODO auto-generated method Stub System.out.println (        "Playservice on Onbind");    return null;        } @Override public void OnCreate () {//TODO auto-generated Method Stub super.oncreate ();        Toast.maketext (This, "Play Service Created", Toast.length_short). Show ();                System.out.println ("Playservice on OnCreate");       Start thread mhandlerthread= new Handlerthread ("Play_service_thread");        Mhandlerthread.start ();    mplayhandler= New Playhandler (Mhandlerthread.getlooper ()); } @Override public void OnStart (Intent Intent, int startid) {//TODO auto-generated method Stub Super              . OnStart (Intent, Startid); OnStart can be used to receive messages from activity//Note that this is still on the main thread toast.maketext (this, "Play Service onStart", Toast.length_shor        T). Show ();        System.out.println ("Playservice on OnStart");                System.out.println ("Playservice thread ID:" +thread.currentthread (). GetId ());      if (intent! = NULL) {Bundle bundle = Intent.getextras ();      if (bundle! = null) {int op = bundle.getint ("op");    Switch (OP) {Case 2://is forwarded to the threading System.out.println via the Message object ("Playservice on OnStart step2");    Message msg = Mplayhandler.obtainmessage ();    Msg.sendtotarget ();      Break }}}//if} @Override public void OnDestroy () {        TODO auto-generated Method Stub Super.ondestroy ();        Toast.maketext (This, "Play Service Stopped", Toast.length_short). Show ();                System.out.println ("Playservice on Destroy");        Exit thread destroy Data Mhandlerthread.quit ();        Mhandlerthread = null;    Mplayhandler = null; }}


Service generation and destruction can be invoked within the activity.

But the service life cycle is not equal to activity, but in the main thread this is where the attention is.




Android Development Research on service

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.