Android Demo tour Activity, Service, and BroadCast count statistics

Source: Internet
Author: User

Android Demo tour Activity, Service, and BroadCast count statistics

Time was in a hurry. in the twinkling of an eye, it took more than half a month to learn about android !! I have written a lot of small demos and summarized them. I also want to leave some footprints in my blog!

Source code download: http://download.csdn.net/detail/harderxin/7761401 reference instance: Lao Luo blog

Implementation function: Statistical counting. We may implement it in many ways. However, this instance uses Activity, Service, and BroadcastReceiver three major knowledge points in android, so it is of reference value;

Knowledge points: 1) Activity and Service life cycle; 2) bindService usage; 3) code registration BroadcastReceiver; 4) learning to use AsyncTask for asynchronous loading

Function logic: See the following flowchart:


After the Activity is started, bind the Service and register the broadcast receiver in the corresponding Activity life cycle. When the user clicks the button, start AsyncTask asynchronous processing logic, that is, Add, then, the results are sent to the broadcast, and the broadcast receiver updates the Activity from time to time after receiving the broadcast;

Functions:


Function details: because the source code is available, I will only explain the core code of this small application:

1) Start Activity and bind Service

// The bindService method starts the counter service CounterService. // serviceConn is an instance of ServiceConnection, after the server starts up, // The system will call the onServiceConnected method in ServiceConnection to pass back the CounterBinder object in the Service to get the corresponding Service. // when we call unBindService to stop the Service, the onServiceDisconnected method Intent bindIntent = new Intent (MainActivity. this, CounterService. class); bindService (bindIntent, serviceConn, Context. BIND_AUTO_CREATE );
// Create the 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, IBinder service) {counterService = (CounterService. counterBinder) service ). getService (); Log. I (TAG, "Counter Service Connected ");}};
Create a Binder object for the Activity in the Service:

// Link between Activity and Service public class CounterBinder extends Binder {public CounterService getService () {return CounterService. this ;}} private final IBinder binder = new CounterBinder (); // this method is executed when the system calls bindService, return a custom Binder object to the system @ Overridepublic IBinder onBind (Intent arg0) {Log. I (TAG, "Counter Service onBind"); return binder ;}

2) register the broadcast Receiver

// Create a broadcast object, receive the 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 only CounterService. BROADCAST_COUNTER_ACTION // type of broadcast interest. When CounterService sends a broadcast, sendBroadcast, this broadcast will be received and processed by the onReceive function in counterActionReceiver // here we register our broadcast in the form of code, you can also register IntentFilter counterActionFilter = new IntentFilter (CounterService. BROADCAST_COUNTER_ACTION); registerReceiver (counterActionReceiver, counterActionFilter );}

3) Click the Count button to asynchronously process the logic and send a broadcast at the same time:

Public void startCounter (int initVal) {// use an Asynchronous Method to count the background. // Why does one use it? Because this counting process can be compared to a time-consuming computing logic, time-consuming operations cannot be performed in the main thread // otherwise, an ANR (Application not responding) may occur) symptom // you can also use Handler and thread combination for AsyncTask
 
  
Task = new AsyncTask
  
   
() {@ Overrideprotected Integer doInBackground (Integer... params) {Log. I (TAG, "doInBackground execute"); Integer initCounter = params [0]; stop = false; while (! Stop) {// The system will automatically call 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 updated values from time to time. 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 updated value from time to time Intent intent = new Intent (BROADCAST_COUNTER_ACTION); intent. putExtra (COUNTER_VALUE, counter={sendbroadcast(intent={{task.exe cute (initVal );}
  
 

4) The broadcast receiver receives the broadcast and updates the interface from time to time:
@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");}
AsyncTask must be instantiated and started in the UI thread. That is to say, in the main thread, the Activity and Service are in the same thread, so we can instantiate and start 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.