Android: How to bind a service to call a service

Source: Internet
Author: User

Android: How to bind a service to call a service

Public class MainActivity extends Activity {private music. myBinder mm; // get the reference of the Service ibinder object in the activity @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} public void open (View view) {Intent intent = new Intent (this, music. class); startService (intent);} public void stop (View view) {Intent intent = new Intent (this, music. class); stopService (intent);} public void play (View view) {Intent intent = new Intent (this, music. class); bindService (intent, new myconn (), BIND_AUTO_CREATE);} private class myconn implements ServiceConnection {@ Overridepublic void onServiceConnected (ComponentName, IBinder service) {System. out. println ("service bound"); // The ibinder object returned by the service will be passed to the callback method mm = (MyBinder) service;} @ Overridepublic void onServiceDisconnected (ComponentName name) of myconn) {}} public void music (View view) {// indirectly calls the method mm in the service using the ibinder object. callchange ("departure ");}

Public class music extends Service {@ Overridepublic IBinder onBind (Intent intent) {System. out. println ("service bound successfully"); // when the service is bound successfully, call the onbind method to return an ibinder object return new MyBinder ();} public class MyBinder extends Binder {public void callchange (String name) {// call the song method classmusc (name) ;}@ Overridepublic void onCreate () {System. out. println ("service enabled"); super. onCreate ();} public void classmusc (String Singname) {Toast. makeText (getApplicationContext (), "song is" + Singname, 1 ). show () ;}@ Overridepublic void onDestroy () {System. out. println ("service destruction"); super. onDestroy ();}}



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.