Communication between android service and activity

Source: Internet
Author: User

Communication between android service and activity

We need to start the service in the following ways:


Intent intent = new Intent();intent.setClass(MainActivity.this, MyService.class);bindService(intent,conn,BIND_AUTO_CREATE);


ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {mService = ((MyService.MyBinder)service).getService();  }};


At this time, the service will execute: onCreate and onBind


Then


We will execute some tasks:

ImageView item_image = (ImageView)findViewById(R.id.item_image);item_image.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mService.setHandler(mHandler);   mService.startCheckIfUpgrade();}});private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case GET_UPGRADE_INFORMATION_COMPLETE:System.out.println("=======notify need upgrade");AlertDialog dialog = getCustomDialog();dialog.show();default:break;}}};

The Service code is:

Public class MyService extends Service {/** thread to execute background task */private Thread mThread = null; /** flag indicates if the service has been stopped */private boolean mStopFlag = false; private static final int GET_UPGRADE_INFORMATION_COMPLETE = 202; /** Handler to get handy from thread */private Handler mHandler = null; public void setHandler (Handler handler) {this. mHandler = handler;} @ Over Ridepublic boolean onUnbind (Intent intent) {System. out. println ("=== service onUnbind"); return super. onUnbind (intent);} public class MyBinder extends Binder {/*** get the instance of the current Service ** @ return */public MyService getService () {return MyService. this ;}} public void startCheckIfUpgrade () {if (mThread = null) {mThread = new UpgradeThread (); mThread. start () ;}@ Overridepublic IBinder onBind (Intent arg0) {inclue M. out. println ("=== = service onBind"); return new MyBinder ();}/*** @ see android. app. service # onCreate () */@ Overridepublic void onCreate () {super. onCreate (); System. out. println ("=== = service onCreate");} private class UpgradeThread extends Thread {/*** @ see java. lang. thread # run () */@ Overridepublic void run () {super. run (); // write it here to the server to check whether the logic of try {Thread needs to be upgraded. sleep (3000);} catch (InterruptedException e) {e. pri NtStackTrace ();} boolean ret = true; if (ret &&! MStopFlag) {Message msg = new Message (); msg. what = GET_UPGRADE_INFORMATION_COMPLETE; mHandler. sendMessage (msg) ;}}/ * (non-Javadoc) * @ see android. app. service # onDestroy () */@ Overridepublic void onDestroy () {System. out. println ("=== ondestroy"); mStopFlag = true; try {if (null! = MThread & mThread. isAlive () {try {mThread. stop () ;}catch (Exception e) {}} mThread = null;} catch (Exception e) {e. printStackTrace ();} super. onDestroy (); System. gc ();}}

After the activity is destroyed, the Service will execute:

OnUnbind and onDestroy

This indicates that the lifecycle of the service is consistent with that of the activity.

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.