Android activity and service for data interaction _android

Source: Internet
Author: User

① from the design point of view:

The Android activity is designed to be very similar to Web pages, from the page's jump through the link, and from the location of the page through the URL, from the individual packaging of each page can be seen, it is mainly responsible for interacting with users.

Service is running in the background, silently provide users with functions, scheduling and co-ordination. If the ground part of a tree is an activity, its huge roots are service. The Android service component is not running in a separate process or thread, and it runs in the main thread of the application just like any other component, and if the service component performs more time-consuming operations, it can cause the main thread to block or suspend animation, which will not respond to the user's actions.

Therefore, time-consuming operations should not be placed in the UI thread, because the UI 5S, broadcast 10s is blocked, can cause ANR.

② from the perspective of use:

Service can not only establish a two-way connection for the activity, provide data and function support, but also can accept the intent request, data analysis processing and function scheduling.

③ from the role played:

The function of the activity is relatively single, mainly is displays the application to have some functions, helps the user to interact with the application, like a person's face. The service may act as a function dispatcher can also act as a function provider, from the trigger to collect information for analysis and processing, and then update the interface, modify data or other operations is a function scheduler, from the choice of input method to consider service play is a function provider. The view component is something that users in Android can actually see, such as buttons, input boxes, and so on, that are inherited from this class, and view only makes sense in containers such as activity, which, in turn, can successfully complete the task of interacting with the user after it is loaded into these view , but the service does not need these fancy things, just wait silently for events to happen or to be sent.

There are two ways to start a service on Android, one is StartService, the other is Bindservice. The life cycle is as follows:

When the StartService is executed, the caller will run in the background without stopservice,service. Call StartService multiple times, the service can only be created once, that is, the service's OnCreate method will only be invoked once. However, each call to the Startservice,onstartcommand method will be invoked.

When executing Bindservice, the caller invokes the Unbindservice method or the caller context does not exist (such as the activity being finish). The OnCreate and Onbind methods are invoked the first time the bindservice is executed, but the OnCreate and Onbind methods are not invoked multiple times when the Bindservice is executed multiple times, that is, the service and the binding service are not created multiple times. Multiple components can be bound to the service at the same time, but when all is unbound, the service is destroyed.

Both the use of StartService and the use of Bindservice requires Unbindservice and stopservice to be invoked at the same time to terminate the service.

There are two ways to interact with a service: one is using broadcast, the other is using Bindservice. This article only describes the Bindservice method.

public class Msgservice extends Service {public msgservice () {}/** * The maximum value of the progress bar */public static final int
  max_progress = 100;

  /** * progress bar of the progress value * * Private int progress = 0;
  /** * Add get () method for Activity call * * @return Download progress/public int getprogress () {return progress; /** * Simulate download task, update once per second/public void Startdownload () {New Thread (new Runnable () {@Override P

          ublic void Run () {while (Progress < max_progress) {progress = 5;
          Progress change notifies the caller if (Onprogresslistener!= null) {onprogresslistener.onprogress (progress);
          try {thread.sleep (1000);
          catch (Interruptedexception e) {e.printstacktrace ();
  }}}). Start ();
  @Override public IBinder onbind (Intent Intent) {return new Mybinder ();
      public class Mybinder extends Binder {public Msgservice GetService () {return msgservice.this;
  } public interface Onprogresslistener {void onprogress (int progress);


  /** * Update the progress of the callback interface * * Private Onprogresslistener Onprogresslistener; /** * Registers the callback interface method for external invocation * * @param onprogresslistener/public void Setonprogresslistener (Onprogresslistener
  Onprogresslistener) {this.onprogresslistener = Onprogresslistener; }

}
public class Mainactivity extends activity {private Button button19;
  Private Msgservice Msgservice;
  private int progress = 0;


  Private ProgressBar Mprogressbar;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 


    Setcontentview (R.layout.activity_main);
    Btnexec = (Button) Findviewbyid (r.id.btnexec);
    Button19 = (Button) Findviewbyid (r.id.button19);


    Mprogressbar = (ProgressBar) Findviewbyid (R.id.progressbar); Button19.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {MS
      Gservice.startdownload ();

    }
    });
    Intent Intent = new Intent (this, msgservice.class);

 

  Bindservice (Intent, mserviceconnection, context.bind_auto_create); } serviceconnection mserviceconnection = new Serviceconnection () {@Override public void Onserviceconnect Ed (componentname componentname, IBinder ibinder) {Msgservice = (MsgService.mybinder) ibinder). GetService (); Msgservice.setonprogresslistener (New Msgservice.onprogresslistener () {@Override public void onprogress (in
        T progress) {mprogressbar.setprogress (progress);
    }
      });


  @Override public void onservicedisconnected (ComponentName componentname) {}};
    @Override protected void OnDestroy () {unbindservice (mserviceconnection);
  Super.ondestroy ();

 }
}

In the example, Msgservice simulates the time-consuming download task, mainactivity the binding service, obtains the download progress by registering the Onprogresslistener callback, and updates the progress bar.

This example activity and service are in the same process, which requires the use of AIDL technology for cross process invocation service.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.