Ui update for services in Android (using binder)

Source: Internet
Author: User

We know that the android program architecture is designed in accordance with the MVC pattern, and the display and logic operations are well separated. The XML file is used to add and layout views. The activity is used to display various views, while the Service implements to display data in the view according to certain logic. Based on this principle, when designing a program, we need to let them perform their respective duties and make reasonable combinations so that the android program we designed can be more efficient, safer, and easier to maintain, of course, this is a very big topic. Here I will only briefly describe the responsibilities of the Service and activity, hoping to play a role in attracting others, of course, it would be an honor to share the same content.

The service is a component running in the background of the android program, such as playing music and downloading the network. All these operations can be completed in the service, but it does not mean that we can only complete them in the service, it can be implemented in the same way in the activity. Why do we need a service? I have been confused once. Later I learned that there are five more process levels in Android (1. foreground process: 2. visible
Process 3. serviceprocess4.background
Process 5. empty procecc) when the system memory resources are insufficient, the system first kills low-level processes to ensure the normal operation of other high-level processes, and the service is in the third level, the covered Activiy is in level 4, so that when we run the program, the current activity will be overwritten for some reason, therefore, many operations in this activity, especially those that require network interaction, may be killed due to insufficient system memory resources. In this way, the data is not completed, and the robustness of the program is not strong enough. If you put all of them in the service, it will be much more secure and the program will be more stable. Of course, the program stability is composed of many factors, which is only one of them. Well, since we put the operation in the service, let's operate it there. Isn't that all done? But when we prepare to do this, we will always be aware of a problem, when we put all these operations into the service for implementation, what should we do with the update of the control in the activity? For example, because there will always be a progress bar during playback, And the download of files should always update the downloads, I don't know how you can solve this problem. I checked it online and found that all the methods are broadcast, that is
Register a broadcast in the activity, and then transmit data between the service and the activity through the broadcast. At the same time, to update the UI, although I have not done so, but I know this is OK, however, I have always realized that this is a bit difficult, and I used a broadcast, according to the effect of my use, I think that broadcasting is not suitable for some update operations from time to time (I have not studied it in depth and did not dare to comment too much). The response was not timely enough. So I tried to update the UI in other ways. Finally, I thought that using the binder object, I didn't need to explain how to implement it. Below I just wrote a simple example. Let's talk about it.

The service used to update the UI

package com.gqs.service;  import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.widget.TextView;  public class UpdateService extends Service {     private int data;     private Handler handler;      @Override     public IBinder onBind(Intent intent) {         // TODO Auto-generated method stub         return new MyBinder();     }      public class MyBinder extends Binder {         public void setDate(final TextView tv, final UpdateData updata) {             new Thread(new MyThread()).start();             handler = new Handler() {                 public void handleMessage(Message msg) {                     updata.update(tv, data);                 }             };         }     }      public class MyThread implements Runnable {          @Override         public void run() {             while (true) {                 data++;                 Message msg = handler.obtainMessage();                 msg.arg1 = data;                 handler.sendMessage(msg);                 try {                     Thread.sleep(1000);                 } catch (InterruptedException e) {                     // TODO Auto-generated catch block                     e.printStackTrace();                 }             }         }      }      public interface UpdateData {         public void update(TextView tv, int data);      } }

Package COM. gqs. activity; import android. app. activity; import android. content. componentname; import android. content. context; 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; import android. widget. textview; import android. widget. toast; impo Rt com. gqs. service. updateService; import COM. gqs. service. updateService. mybinder; import COM. gqs. service. updateService. updatedata; public class servicetoactivityactivity extends activity {/** called when the activity is first created. */private textview TV; private UpdateService. mybinder binder; private button btnstart; private serviceconnection conn = new serviceconnection () {@ override public void o Nservicedisconnected (componentname name) {// todo auto-generated method stub} @ override public void onserviceconnected (componentname, ibinder Service) {// todo auto-generated method stub binder = (mybinder) service; TV. settext ("connected") ;}}; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); btnstart = (button) findviewby ID (R. id. btnstart); TV = (textview) findviewbyid (R. id. textview); intent = new intent (this, UpdateService. class); bindservice (intent, Conn, context. bind_auto_create); btnstart. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {// todo auto-generated method stub if (binder! = NULL) {binder. setdate (TV, new updatedata () {@ override public void Update (textview TV, int data) {// todo auto-generated method stub TV. settext (Data + "") ;}}) ;}else {toast. maketext (getapplicationcontext (), "connection failed", 1 ). show () ;}}) ;}@ override protected void ondestroy () {// todo auto-generated method stub unbindservice (conn); super. ondestroy ();}}

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: Id = "@ + ID/textview" Android: text = "@ string/Hello"/> <button Android: TEXT = "start" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: Id = "@ + ID/btnstart"/> </linearlayout>

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.