Android: Communication for activities and services

Source: Internet
Author: User

9.3.3 activities and services for communication

In the previous section we learned how to start and stop the service, do not know if you have found that although the service is launched in the activity, but after the start of the service, activities and services are basically no relationship. Indeed, we call the StartService () method in the activity to start the MyService service, and then the MyService onCreate () and Onstartcommand () methods are executed. After that, the service will always be running, but the logic of what is running will not control the activity. This is similar to the event Notification Service: "You can start up!" "Then the service goes to work on its own, but the activity doesn't know what the service is going to do, and how it's done."

So is there any way to make activities and services more closely related? For example, in the event of directing the service to do, the service to do. Of course, this requires the use of the Onbind () method that we have just overlooked.

For example, at present we want to provide a download function in MyService, and then in the event can decide when to start the download, and to view the download progress at any time. The idea for this is to create a dedicated Binder object to manage the download functionality and modify the code in MyService as follows:

public class MyService extends Service {

Private Downloadbinder Mbinder = new Downloadbinder ();

Class Downloadbinder extends Binder {

Public void Startdownload () {

LOG.D ("MyService", "Startdownload executed");

}

public int getprogress () {

LOG.D ("MyService", "getprogress executed");

return 0;

}

}

@Override

Public IBinder Onbind (Intent Intent) {

return mbinder;

}

......

}

As you can see, here we create a new Downloadbinder class and let it inherit from Binder, and then provide a way to start downloading and view the download progress within it. Of course, this is only two simulation methods, and does not implement the real function, we in the two methods to print a row of logs.

Next, an instance of Downloadbinder was created in MyService and then returned in the Onbind () method, so that the work in MyService is complete.

Here's a look at how to invoke these methods in the service in the event. First you need to add two buttons to the layout file to modify the code in the Activity_main.xml as follows:

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "

android:orientation= "Vertical" >

......

<button android:id= "@+id/bind_service" android:layout_width= "match_parent" android:layout_height= "wrap_content "Android:text=" Bind Service "/>

<button android:id= "@+id/unbind_service" android:layout_width= "match_parent" android:layout_height= "Wrap_ Content "android:text=" Unbind Service "/>

</LinearLayout>

The two buttons are used to bind the service and unbind the service, so who needs to go and service binding? Of course it's the activity. When an activity and service are bound, it is possible to invoke the methods provided by the Binder in the service. Modify the code in the mainactivity as follows:

Public class Mainactivity extends Activity implements Onclicklistener {

Private Button StartService; Private Button StopService; Private Button Bindservice; Private Button Unbindservice;

Private Myservice.downloadbinder Downloadbinder;

Private Serviceconnection connection = new Serviceconnection () {

@Override

public void onservicedisconnected (componentname name) {

}

@Override

public void onserviceconnected (componentname name, IBinder service) {Downloadbinder = (Myservice.downloadbinder) Service Downloadbinder.startdownload ();

Downloadbinder.getprogress ();

}

};

@Override

protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);

......

Bindservice = (Button) Findviewbyid (R.id.bind_service); Unbindservice = (Button) Findviewbyid (R.id.unbind_service); Bindservice.setonclicklistener (this);

Unbindservice.setonclicklistener (this);

}

@Override

public void OnClick (View v) {

Switch (V.getid ()) {

......

Case R.id.bind_service:

Intent bindintent = new Intent (this, myservice.class);

Bindservice (bindintent, Connection, bind_auto_create);// Binding Services

Break

Case R.id.unbind_service:

Unbindservice (connection);// Unbind Service

Break

Default

Break

}

}

}

As you can see, here we first create an anonymous class of Serviceconnection, which overrides the Onserviceconnected () method and the Onservicedisconnected () method, respectively, in the Activity and service Called when binding is successful and unbound. In the Onserviceconnected () method, we also get an example of downloadbinder by downward transformation, and with this example, the relationship between the activity and the service becomes very close. Now we can invoke any public method in the activity based on a specific scenario, that is, the function of what the command service does and what the service will do Downloadbinder. This is still a simple test, and the Downloadbinder startdownload () and Getprogress () methods are called in the Onserviceconnected () method.

Of course, activities and services are not yet binding, and this feature is done in the BIND Service button's Click event. As you can see, we're still building a Intent object, and then calling the Bindservice () method to bind Mainactivity and MyService. The Bindservice () method receives three parameters, the first parameter is the Intent object that was just built, the second argument is an instance of the Serviceconnection created earlier, and the third parameter is a flag bit, which is passed in Bind_auto_create Indicates that the service is created automatically after the activity and the service are bound. This will cause the OnCreate () method in MyService to be executed, but the Onstartcommand () method will not execute.

And what if we want to unbind the activity from the service? Call the Unbindservice () method, which is the function that is implemented in the Click event of the Unbind Service button.

Now let's run the program again, as shown in interface 9.9.

Figure 9.9

Click on the Bind Service button and observe print log 9.10 in LogCat:

Figure 9.10

As you can see, the first is that the MyService onCreate () method is executed, and then the Startdownload () and Getprogress () methods are executed, indicating that we have successfully invoked the methods provided in the service in the event. It is also important to note that any service is common throughout the application, that is, myservice can be bound not only with mainactivity, but also with any other activity, and when the bindings are complete they can get the same Downloadbinder instance.

Android: Communication for activities and services

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.