Android Demo Tour Activity, Service, broadcast implementation count statistics

Source: Internet
Author: User

Time in a hurry, the blink of an eye is big half a month passed, learn the truth of Android hard and long Ah!! I wrote a lot of small demo, summary summary, but also in the blog to leave some footprints it!

Source code Download: http://download.csdn.net/detail/harderxin/7761401 Reference example: Lao Luo blog

Implementation function: Statistical count, we may have a lot of ways to achieve it, but this example uses activity, Service, Broadcastreceiver in Android three big knowledge points, so think it is more reference value;

can learn the knowledge point: 1) Activity, service life cycle; 2) Bindservice usage; 3) code Registration BROADCASTRECEIVER;4) Learn to use the asynchronous load class asynctask

Functional logic: Refer to the following flowchart:


After the activity is started, the service and registered broadcast receivers are bound in the corresponding activity lifecycle, and when the user taps the button, the Asynctask asynchronous processing logic is initiated, that is, addend, and the results are sent to the broadcast. The broadcast receiver updates the activity after receiving the broadcast;

Implementation features:


Functional detail: Because of the source code, so I only explain the small application of the core code:

1) Start activity, bind service

        The Bindservice method will start up the counter service Counterservice        //serviceconn to an instance of Serviceconnection, after the server is started        // The system will call Serviceconnection inside the Onserviceconnected method to the service in//        Counterbinder object back, get the corresponding service        // When we call Unbindservice to stop the service, it calls its Onservicedisconnected method        Intent bindintent=new Intent (Mainactivity.this, Counterservice.class);        Bindservice (Bindintent, Serviceconn, context.bind_auto_create);
    Create service Connection object    private serviceconnection serviceconn=new serviceconnection () {    @Overridepublic void onservicedisconnected (componentname name) {counterservice=null; LOG.I (TAG, "Counter Service Disconnected");} @Overridepublic void onserviceconnected (componentname name, IBinder service) {counterservice= ( Counterservice.counterbinder) service). GetService (); LOG.I (TAG, "Counter Service Connected");};
Create a service that deals with activityBinder object:

Activity and Service link public class Counterbinder extends Binder{public counterservice getService () {return Counterservice.this;}} Private final IBinder binder=new Counterbinder (); When the system calls Bindservice, the method is executed, returning a custom binder object to the system @overridepublic IBinder Onbind (Intent arg0) {log.i (TAG, "Counter Service onbind"); return binder;}

2) Register the broadcast recipient

Create a broadcast object, receive broadcast information sent from Counterservice, and display the corresponding information on the interface private Broadcastreceiver counteractionreceiver=new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent Intent) {int Counter=intent.getintextra ( Counterservice.counter_value, 0); Count=counter;countertext.settext (count+ ""); LOG.I (TAG, "Receive counter Event");}; @Overrideprotected void Onresume () {super.onresume (); LOG.I (TAG, "mainactivity onresume");//Register a broadcast receiver, which specifies that only the counterservice.broadcast_counter_action//type of broadcast is interested, When Counterservice sends a post-broadcast sendbroadcast, the broadcast is received by the OnReceive function in the counteractionreceiver////register our broadcast in the form of code, We can also register the corresponding intentfilter counteractionfilter=new intentfilter (counterservice.broadcast_counter_action) in XML; Registerreceiver (Counteractionreceiver, counteractionfilter);}

3) Click the Count button to process the logic asynchronously and send the broadcast at all times:

public void Startcounter (int initval) {//Use async for background counting//why use it? Because of this counting process we can analogy a time-consuming calculation logic, time-consuming operation can not be carried out in the main thread//otherwise there will be ANR (application not responding) phenomenon// You can also use handler with a thread to Asynctask<integer, Integer, integer> task=new asynctask<integer, Integer, integer> () {@Overrideprotected integer doinbackground (integer ... params) {log.i (TAG, "doinbackground execute"); integer Initcounter=params[0];stop=false;while (!stop) {//Call this method the system automatically calls the Onprogressupdate method Publishprogress (initcounter); try {thread.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();} initcounter++;} return initcounter;} @Overrideprotected void Onprogressupdate (Integer ... values) {log.i (TAG, "onprogressupdate execute"); Super.onprogressupdate (values); int counter=values[0];//broadcasts the values that are constantly updated intent intent=new intent (broadcast_counter_ ACTION); Intent.putextra (Counter_value, COUNTER); Sendbroadcast (intent);} @Overrideprotected void OnPostExecute (Integer result) {log.i (TAG, "OnPostExecute execute"); int counter=result;// Broadcast the values that are constantly updated intentIntent=new Intent (broadcast_counter_action); Intent.putextra (Counter_value, COUNTER); Sendbroadcast (intent);}}; Task.execute (initval);}

4) The broadcast receiver receives the broadcast and updates the interface at all times:
@Overridepublic void OnReceive (context context, Intent Intent) {int Counter=intent.getintextra (counterservice.counter _value, 0); Count=counter;countertext.settext (count+ ""); LOG.I (TAG, "Receive counter Event");}
because Asynctask and startup must be in the UI thread, that is, in the main thread, the activity and service are in the main thread, so we can instantiate and start the asynctask! in the service

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.