Activity and Service, activityservice

Source: Internet
Author: User

Activity and Service, activityservice

There are two methods for Android to start a Service: startService and bindService. The lifecycle is as follows:

 

When you execute startService, if the caller does not have stopService, the Service will continue to run in the background. Multiple call of startService, the Service can be created only once, that is, the onCreate method of the Service will be called only once. However, the onStartCommand method is called every time you call startService.

When the bindService is executed, the caller calls the unbindService method or the caller Context does not exist (for example, the Activity is finished ). When bindService is executed for the first time, the onCreate and onBind methods will be called. However, when bindService is executed multiple times, the onCreate and onBind methods will not be called multiple times, that is, the service will not be created and bound multiple times.

When both startService and bindService are used, the Service must be terminated only when both unbindService and stopService are called.

 

There are two ways for Activity to interact with Service: broadcast and bindService. This document only describes the bindService method.

 

 

1 public class MsgService extends Service {2 public MsgService () {3} 4 5/** 6 * maximum progress bar value 7 */8 public static final int MAX_PROGRESS = 100; 9/** 10 * progress bar progress value 11 */12 private int progress = 0; 13 14/** 15 * Add the get () method, for the Activity to call 16*17 * @ return download progress 18 */19 public int getProgress () {20 return progress; 21} 22 23/** 24 * to simulate a download task, update 25 */26 public void startDownLoad () {27 new Thread (new Runnable () {2 8 29 @ Override30 public void run () {31 while (progress <MAX_PROGRESS) {32 progress + = 5; 33 34 // notify the caller of progress changes 35 if (onProgressListener! = Null) {36 onProgressListener. onProgress (progress); 37} 38 39 try {40 Thread. sleep (1000); 41} catch (InterruptedException e) {42 e. printStackTrace (); 43} 44 45} 46} 47 }). start (); 48} 49 50 @ Override51 public IBinder onBind (Intent intent) {52 return new MyBinder (); 53} 54 55 public class MyBinder extends Binder {56 public MsgService getService () {57 return MsgService. this; 58} 59} 60 61 public interface OnProgressListener {62 void onProgress (int progress ); 63} 64 65/** 66 * Update Progress callback interface 67 */68 private OnProgressListener onProgressListener; 69 70 71/*** 72 * method of registering the callback interface, for external calls 73*74 * @ param onProgressListener75 */76 public void setOnProgressListener (OnProgressListener onProgressListener) {77 this. onProgressListener = onProgressListener; 78} 79 80}

 

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) {                msgService.startDownLoad();            }        });        Intent intent = new Intent(this, MsgService.class);        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);    }    ServiceConnection mServiceConnection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {            msgService = ((MsgService.MyBinder) iBinder).getService();            msgService.setOnProgressListener(new MsgService.OnProgressListener() {                @Override                public void onProgress(int progress) {                    mProgressBar.setProgress(progress);                }            });        }        @Override        public void onServiceDisconnected(ComponentName componentName) {        }    };    @Override    protected void onDestroy() {        unbindService(mServiceConnection);        super.onDestroy();    }}

 

In this example, MsgService simulates time-consuming download tasks, binds MainActivity to the service, registers the OnProgressListener callback to get the download progress, and updates the progress bar.

 

In this example, the Activity and Service are in the same process. For cross-process Service calling, AIDL technology is required.

 

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.