Android-service interaction with the activity

Source: Internet
Author: User

One of the four components of service-android. Personal "backend service" means that its own operation does not depend on the user's visual UI interface

In practical development, we often need the service and activity to pass data to each other to maintain the program's operation.

Get to know the service life cycle first.

Create a new class relay service:

package Com.example.myservicedemo.service;import Android.app.service;import Android.content.intent;import Android.os.binder;import android.os.ibinder;/** * Service class (required to register services in the project manifest file) * * @author Lenovo * */public class MyService Exten    DS Service {@Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;} /** * Service created when called */@Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate ();    System.out.println ("=========oncreate======");} /** * Service Start call */@Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generate D Method StubSystem.out.println ("=========onstartcommand======"); return Super.onstartcommand (Intent, flags, Startid    );} /** * Service is destroyed when called */@Overridepublic void OnDestroy () {//TODO auto-generated method StubSystem.out.println ("======== =ondestroy====== "); Super.ondestroy ();}} 

When you create the above class and inherit the service, only the Onbind () method is overridden, and the other method is my manual handwriting, in order to understand the service life cycle

Mainactivity (set two buttons to start and stop a service):

Package Com.example.myservicedemo.ui;import Com.example.myservicedemo.r;import Com.example.myservicedemo.service.myservice;import Com.example.myservicedemo.service.MyService.DownLoadBinder; Import Android.app.activity;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;public class Mainactivity extends Activity Implements Onclicklistener {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); Button Btn_start = (button) Findviewbyid (R.id.btn_start); Button Btn_stop = (button) Findviewbyid (r.id.btn_stop); Btn_start.setonclicklistener (this); Btn_ Stop.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubint id = v.getid (); switch (ID) {/* * * Turn on service click event */ca Se r.id.btn_start:iNtent startintent = new Intent (this, myservice.class); StartService (startintent); break;/* * Stop service click event */case r.id.btn_ Stop:intent stopintent = new Intent (this, myservice.class); StopService (stopintent); break;default:break;}}}

  remember that services in Android need to be registered in the project manifest file (Androidstudio can be automated and eclipse needs to be added manually):

<service android:name= "The package name where the service class sits. MyService "></service>

Run the program at this time, click on the service when the output is: (I output multiple onstartcommand () is because I clicked the service button repeatedly)

You can see that the first time the service was opened, the OnCreate () method and the Onstartcommand () method were called, and only the Onstartcommand () method was called when the service was started multiple times.

So

The onCreate () method is called when the service is created.

The Onstartcommand () method will be called every time the service is started.

The Ondestory () method is called when the service is stopped

When you click Stop Service, the output

Another way to start a service is Bindservice ();

The MyService class should be changed at this time:

Package Com.example.myservicedemo.service;import Android.app.service;import Android.content.intent;import Android.os.binder;import android.os.ibinder;/** * Service class (required to register services in the project manifest file) * * @author Lenovo * */public class MyService Exten DS Service {private Downloadbinder downloadbinder=new downloadbinder (); @Overridepublic ibinder Onbind (Intent Intent) { TODO auto-generated Method StubSystem.out.println ("=====onbind====="); return downloadbinder;} /** * Inner class inherits Binder * @author Lenovo * */public class Downloadbinder extends Binder{public void Startdownload () {SYSTEM.OUT.P Rintln ("=====startdownload () =====");}    public void Getprogress () {System.out.println ("=====getprogress () =====");}} /** * Service created when called */@Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate ();    System.out.println ("=========oncreate======");} /** * Service Start call */@Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generate D method StubSystem.out.println ("=========onstartcommand====== "); return Super.onstartcommand (Intent, flags, Startid);} /** * Service is destroyed when called */@Overridepublic void OnDestroy () {//TODO auto-generated method StubSystem.out.println ("======== =ondestroy====== "); Super.ondestroy ();}}

Above the code compared to the first one is more an inner class Downloadbinder inherits IBinder and declares two methods, and the other is to change the return value of the Onbind method to a variable of downloadbinder type

The activity Bindservice method starts the service time generally needs to pass the data, the core is in the Onbind () method, looks down

Mainactivity Add two buttons: Bind Service and Unbind service

Package Com.example.myservicedemo.ui;import Com.example.myservicedemo.r;import Com.example.myservicedemo.service.myservice;import Com.example.myservicedemo.service.MyService.DownLoadBinder; Import Android.app.activity;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;public class Mainactivity extends Activity    Implements Onclicklistener {private Myservice.downloadbinder downloadbinder;  Private MyService MyService; Our own service @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button Btn_start = (button) Findviewbyid (R.id.btn_start); Button Btn_stop = (button) Findviewbyid (r.id.btn_stop); Button Btn_bind = (button) Findviewbyid (R.id.btn_bind); Button Btn_unbind = (button) Findviewbyid (R.id.btn_unbIND); Btn_start.setonclicklistener (this), Btn_stop.setonclicklistener (This), Btn_bind.setonclicklistener (this); Btn_unbind.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubint id = v.getid (); switch (ID) {/* * * Turn on service click event */ca Se r.id.btn_start:intent startintent = new Intent (this, myservice.class); StartService (startintent); break;/* * Stop Service Click event */case r.id.btn_stop:intent stopintent = new Intent (this, myservice.class); StopService (stopintent); break;/* * Bind Service Click event */case r.id.btn_bind:intent bindintent = new Intent (this, myservice.class); Bindservice (bindintent, connection, Bind_ auto_create); break;/* * Unbind Service Click event */case r.id.btn_unbind:unbindservice (connection); break;default:break;}} Private serviceconnection connection=new serviceconnection () {/** * Service unbound when called */@Overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated method stub}/** * Bind service when called */@Overridepublic void onSe rviceconnected (componentname name, IBiNDEr service) {//TODO auto-generated Method Stub//myservice= ((downloadbinder) service). Downloadbinder= ( Downloadbinder) service;/* * Call Downloadbinder method to implement the parameter transfer */downloadbinder.startdownload (); Downloadbinder.getprogress ();}};}

After running click the BIND service after the output is as follows:

Indicates that the service was successfully bound and the data was passed and the Ondestory () method output was clicked when unbinding the service

But this method seems to only pass the data once,,, uncomfortable,,,, such as the background in real-time update things, activity needs real-time access to it???

Finding data is mostly in the following ways:

1. Use the interface callback method, the activity implements the corresponding interface, service through the interface callback, more flexible

2. Use the broadcast

This blog mainly introduces the first method, why not introduce the second kind??? --unwilling to introduce, not like.

MyService and Mainactivity code that uses interface callback method I am the note in detail after the paste, you can read the comments

MyService Code:

Package Com.example.myservicedemo.service;import Java.util.timer;import Java.util.timertask;import Android.app.service;import android.content.intent;import Android.os.binder;import android.os.IBinder;/** * Service class (required to register services in the project manifest file) * * @author Lenovo * */public class MyService extends service {private Downloadbinder Downloadbin    Der=new Downloadbinder (); /** * Callback */private Callback callback;/** * Timer Real-time Update data */private Timer mtimer=new timer ();/** * */private int num; @Overr Idepublic ibinder onbind (Intent Intent) {//TODO auto-generated method StubSystem.out.println ("=====onbind====="); return downloadbinder;} /** * Inner class inherits Binder * @author Lenovo * */public class Downloadbinder extends binder{/** * Declares method return value is MyService itself * @return */pu    Blic MyService GetService () {return myservice.this;}}  /** * Service created when called */@Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate ();/* * Execute Timer 2000 milliseconds after execution, 5000 milliseconds to execute */mtimer.schedule (task, 0, 1000);} /** * Provides interface callback method * @param calLback */public void Setcallback (Callback Callback) {this.callback = Callback;} /** * */timertask task = new TimerTask () {@Overridepublic void Run () {//TODO auto-generated method Stubnum++;if (callback! =null) {/* * Get the latest data */callback.getnum (num);}}};/     * * Callback Interface * * @author Lenovo * */public static interface Callback {/** * get real-time updated data * * @return */void getnum (int num);} /** * Service is destroyed when called */@Overridepublic void OnDestroy () {//TODO auto-generated method stubSystem.out.println ("= = = =====ondestroy====== ");/** * Stop Timer */mtimer.cancel (); Super.ondestroy ();}}

mainactivity code:

Package Com.example.myservicedemo.ui;import Com.example.myservicedemo.r;import Com.example.myservicedemo.service.myservice;import Com.example.myservicedemo.service.myservice.callback;import Com.example.myservicedemo.service.myservice.downloadbinder;import Android.app.activity;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;public class Mainactivity extends Activity implements Onclicklistener {private myservice.   Downloadbinder Downloadbinder;  Private MyService MyService; Our own service @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button Btn_start = (button) Findviewbyid (R.id.btn_start); Button Btn_stop = (button) Findviewbyid (r.id.btn_stop); Button Btn_bind = (button) Findviewbyid (r.id.btN_bind); Button Btn_unbind = (button) Findviewbyid (r.id.btn_unbind); Btn_start.setonclicklistener (this); Btn_ Stop.setonclicklistener (This), Btn_bind.setonclicklistener (This), Btn_unbind.setonclicklistener (this);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubint id = v.getid (); switch (ID) {/* * * Turn on service click event */ca Se r.id.btn_start:intent startintent = new Intent (this, myservice.class); StartService (startintent); break;/* * Stop Service Click event */case r.id.btn_stop:intent stopintent = new Intent (this, myservice.class); StopService (stopintent); break;/* * Bind Service Click event */case r.id.btn_bind:intent bindintent = new Intent (this, myservice.class); Bindservice (bindintent, connection, Bind_ auto_create); break;/* * Unbind Service Click event */case r.id.btn_unbind:unbindservice (connection); break;default:break;}} Private serviceconnection connection=new serviceconnection () {/** * Service unbound when called */@Overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated method stub}/** * Bind service when calling */@overridepublic void onserviceconnected (componentname name, IBinder service) {//TODO auto-generated method Stubdownloadbinder = (downloadbinder) service; MyService Service2 = Downloadbinder.getservice ();/** * Implements callbacks to get real-time refreshed data */service2.setcallback (new Callback () {@ overridepublic void getnum (int num) {//TODO auto-generated method StubSystem.out.println ("====num====" +num);}});}};}

The results should be output after the run (the output is updated with the number of NUM in the service):

problems encountered during the period:

Invalid after Bindservice, the Onbind () method in the MyService class was not called

Workaround: In this case your activity should be inherited by tabbaractivity, when the binding service is called to write this form:

This.getapplicationcontext (). Bindservice (Intent, mconnection, bind_auto_create);

In recent days to use, summed up, hope can bring help for everyone, there are mistakes and ask the big God correct.

Android-service interaction with the activity

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.