Home | History | Annotate | Download | only in components
      1 page.title= 
      2 parent.title=
      3 parent.link=services.html
      4 @jd:body
      5 
      6 
      7 <div id="qv-wrapper">
      8 <ol id="qv">
      9 <h2> </h2>
     10 <ol>
     11   <li><a href="#Basics"></a></li>
     12   <li><a href="#Creating">  </a>
     13     <ol>
     14       <li><a href="#Binder">  Binder</a></li>
     15       <li><a href="#Messenger">  Messenger</a></li>
     16     </ol>
     17   </li>
     18   <li><a href="#Binding">  </a></li>
     19   <li><a href="#Lifecycle">    </a></li>
     20 </ol>
     21 
     22 <h2> </h2>
     23 <ol>
     24   <li>{@link android.app.Service}</li>
     25   <li>{@link android.content.ServiceConnection}</li>
     26   <li>{@link android.os.IBinder}</li>
     27 </ol>
     28 
     29 <h2></h2>
     30 <ol>
     31   <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code
     32       RemoteService}</a></li>
     33   <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
     34       LocalService}</a></li>
     35 </ol>
     36 
     37 <h2>. :</h2>
     38 <ol>
     39   <li><a href="{@docRoot}guide/components/services.html"></a></li>
     40 </ol>
     41 </div>
     42 
     43 
     44 <p>     -.     
     45 (, )   ,  ,            
     46 IPC.    ,    
     47   .       .</p>
     48 
     49 <p>   ,    ,   
     50     .      <a href="{@docRoot}guide/components/services.html"></a>,   
     51  , ,      ,   
     52       ..</p>
     53 
     54 
     55 <h2 id="Basics"></h2>
     56 
     57 <p>      {@link android.app.Service},  
     58         .    
     59 ,       {@link android.app.Service#onBind onBind()}. 
     60    {@link android.os.IBinder}.    ,
     61        .</p>
     62 
     63 <div class="sidebox-wrapper">
     64 <div class="sidebox">
     65   <h3>   </h3>
     66 
     67 <p>    <a href="{@docRoot}guide/components/services.html"></a>,
     68   ,    ,  .  ,    
     69    {@link android.content.Context#startService startService()},   
     70   ,            {@link
     71 android.content.Context#bindService bindService()}.
     72   <p>     ,    
     73  <em></em>       .   
     74    ,   {@link android.app.Service#stopSelf stopSelf()}  {@link
     75 android.content.Context#stopService stopService()}.</p>
     76 
     77 <p>  ,       {@link android.app.Service#onBind onBind()},
     78 <em> </em> {@link android.app.Service#onStartCommand onStartCommand()},    
     79    . ,           
     80  ,     .  ,       
     81 ,         .   
     82         ,    .</p>
     83 
     84 <p>   ,  <a href="#Lifecycle">   
     85 </a>.         ,   
     86  .</p>
     87 </div>
     88 </div>
     89 
     90 <p>        {@link android.content.Context#bindService
     91 bindService()}.        {@link
     92 android.content.ServiceConnection},       .  {@link
     93 android.content.Context#bindService bindService()}    , 
     94 ,   Android   
     95 -,    {@link
     96 android.content.ServiceConnection#onServiceConnected onServiceConnected()}  {@link
     97 android.content.ServiceConnection},    {@link android.os.IBinder}, 
     98       .</p>
     99 
    100 <p>       .    
    101 {@link android.app.Service#onBind onBind()}      {@link android.os.IBinder}
    102     .        {@link android.os.IBinder}  
    103  ,   ,     {@link android.app.Service#onBind onBind()}.</p>
    104 
    105 <p>      ,    ( 
    106        {@link android.content.Context#startService startService()}).</p>
    107 
    108 <p>         ,
    109       {@link android.app.Service#onBind onBind()}.  
    110     {@link android.os.IBinder} .      
    111 .</p>
    112 
    113 
    114 
    115 <h2 id="Creating">  </h2>
    116 
    117 <p>  ,  ,   {@link android.os.IBinder},
    118    ,        . 
    119     :</p>
    120 
    121 <dl>
    122   <dt><a href="#Binder">  Binder</a></dt>
    123   <dd>          ,       ,   
    124 ( ),       {@link android.os.Binder}
    125      
    126 {@link android.app.Service#onBind onBind()}.    {@link android.os.Binder},
    127             ,     {@link android.os.Binder},
    128    {@link android.app.Service}.
    129   <p>   ,        
    130  .         , 
    131          .</dd>
    132 
    133   <dt><a href="#Messenger">  Messenger</a></dt>
    134   <dd> ,        ,   
    135    {@link android.os.Messenger}.  , 
    136   {@link android.os.Handler},     {@link
    137 android.os.Message}.   {@link android.os.Handler}
    138     {@link android.os.Messenger}, ,   ,    {@link android.os.IBinder},
    139            {@link
    140 android.os.Message}.  ,     {@link android.os.Messenger}  
    141 ,      .
    142   <p>      ,  {@link
    143 android.os.Messenger}        ,     
    144   .</p>
    145   </dd>
    146 
    147   <dt>  AIDL</dt>
    148   <dd>AIDL (Android Interface Definition Language)       
    149 ,           
    150    (IPC).      {@link android.os.Messenger}    AIDL,   
    151  .    ,  {@link android.os.Messenger}    
    152      ,       . , 
    153  ,       ,   AIDL
    154 .            .
    155   <p>  AIDL , 
    156   {@code .aidl},    .     SDK Android 
    157   ,       ,  
    158      .</p>
    159   </dd>
    160 </dl>
    161 
    162   <p class="note"><strong>.</strong>    <strong> </strong>  AIDL 
    163    ,       , ,   ,  
    164    .  AIDL     ,
    165              .     , 
    166    AIDL ,   
    167 <a href="{@docRoot}guide/components/aidl.html">AIDL</a>.</p>
    168 
    169 
    170 
    171 
    172 <h3 id="Binder">  Binder</h3>
    173 
    174 <p>            ,
    175     {@link android.os.Binder},      
    176      .</p>
    177 
    178 <p class="note"><strong>.</strong>       ,      
    179    ,     . ,     
    180  ,         , 
    181     .</p>
    182 
    183 <p>   :</p>
    184 <ol>
    185   <li>      {@link android.os.Binder}   :
    186     <ul>
    187       <li>   ,    ; </li>
    188       <li>     {@link android.app.Service}, 
    189  ,    ; </li>
    190       <li>    ,   ,   ,
    191    .</li>
    192     </ul>
    193   <li>    {@link android.os.Binder}     {@link
    194 android.app.Service#onBind onBind()}.</li>
    195   <li>    {@link android.os.Binder}     {@link
    196 android.content.ServiceConnection#onServiceConnected onServiceConnected()} 
    197         .</li>
    198 </ol>
    199 
    200 <p class="note"><strong>.</strong>           
    201 ,               API-.  , 
    202           ,      -
    203   .</p>
    204 
    205 <p>   ,         
    206 {@link android.os.Binder}:</p>
    207 
    208 <pre>
    209 public class LocalService extends Service {
    210     // Binder given to clients
    211     private final IBinder mBinder = new LocalBinder();
    212     // Random number generator
    213     private final Random mGenerator = new Random();
    214 
    215     /**
    216      * Class used for the client Binder.  Because we know this service always
    217      * runs in the same process as its clients, we don't need to deal with IPC.
    218      */
    219     public class LocalBinder extends Binder {
    220         LocalService getService() {
    221             // Return this instance of LocalService so clients can call public methods
    222             return LocalService.this;
    223         }
    224     }
    225 
    226     &#64;Override
    227     public IBinder onBind(Intent intent) {
    228         return mBinder;
    229     }
    230 
    231     /** method for clients */
    232     public int getRandomNumber() {
    233       return mGenerator.nextInt(100);
    234     }
    235 }
    236 </pre>
    237 
    238 <p> {@code LocalBinder}     {@code getService()},    
    239    {@code LocalService}.        
    240 . ,     {@code getRandomNumber()}  .</p>
    241 
    242 <p>   ,      {@code LocalService}    {@code getRandomNumber()}
    243   :</p>
    244 
    245 <pre>
    246 public class BindingActivity extends Activity {
    247     LocalService mService;
    248     boolean mBound = false;
    249 
    250     &#64;Override
    251     protected void onCreate(Bundle savedInstanceState) {
    252         super.onCreate(savedInstanceState);
    253         setContentView(R.layout.main);
    254     }
    255 
    256     &#64;Override
    257     protected void onStart() {
    258         super.onStart();
    259         // Bind to LocalService
    260         Intent intent = new Intent(this, LocalService.class);
    261         bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    262     }
    263 
    264     &#64;Override
    265     protected void onStop() {
    266         super.onStop();
    267         // Unbind from the service
    268         if (mBound) {
    269             unbindService(mConnection);
    270             mBound = false;
    271         }
    272     }
    273 
    274     /** Called when a button is clicked (the button in the layout file attaches to
    275       * this method with the android:onClick attribute) */
    276     public void onButtonClick(View v) {
    277         if (mBound) {
    278             // Call a method from the LocalService.
    279             // However, if this call were something that might hang, then this request should
    280             // occur in a separate thread to avoid slowing down the activity performance.
    281             int num = mService.getRandomNumber();
    282             Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    283         }
    284     }
    285 
    286     /** Defines callbacks for service binding, passed to bindService() */
    287     private ServiceConnection mConnection = new ServiceConnection() {
    288 
    289         &#64;Override
    290         public void onServiceConnected(ComponentName className,
    291                 IBinder service) {
    292             // We've bound to LocalService, cast the IBinder and get LocalService instance
    293             LocalBinder binder = (LocalBinder) service;
    294             mService = binder.getService();
    295             mBound = true;
    296         }
    297 
    298         &#64;Override
    299         public void onServiceDisconnected(ComponentName arg0) {
    300             mBound = false;
    301         }
    302     };
    303 }
    304 </pre>
    305 
    306 <p>   ,        
    307 {@link android.content.ServiceConnection}    {@link
    308 android.content.ServiceConnection#onServiceConnected onServiceConnected()}. 
    309            .</p>
    310 
    311 <p class="note"><strong>.</strong>          ,
    312          (,   ).</p>
    313 
    314 <p>    ,   <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
    315 LocalService.java}</a>  <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html">{@code
    316 LocalServiceActivities.java}</a>,  <a href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p>
    317 
    318 
    319 
    320 
    321 
    322 <h3 id="Messenger">  Messenger</h3>
    323 
    324 <div class="sidebox-wrapper">
    325 <div class="sidebox">
    326   <h4>  AIDL</h4>
    327   <p>     ,   {@link android.os.Messenger}  
    328      AIDL,   {@link android.os.Messenger} 
    329      ,   ,    AIDL,     ,
    330     .</p>
    331   <p>       ,     {@link
    332 android.os.Messenger}      .   ,
    333    ,      <a href="{@docRoot}guide/components/aidl.html">AIDL</a>.</p>
    334 </div>
    335 </div>
    336 
    337 <p> ,      ,       
    338 {@link android.os.Messenger}.  
    339      (IPC)    AIDL.</p>
    340 
    341 <p>   ,     {@link android.os.Messenger}:</p>
    342 
    343 <ul>
    344   <li>   {@link android.os.Handler},      
    345   .</li>
    346   <li> {@link android.os.Handler}     {@link android.os.Messenger}
    347 (     {@link android.os.Handler}).</li>
    348   <li> {@link android.os.Messenger}   {@link android.os.IBinder},  
    349     {@link android.app.Service#onBind onBind()}.</li>
    350   <li>    {@link android.os.IBinder}     {@link android.os.Messenger}
    351 (    {@link android.os.Handler} ),     
    352 {@link android.os.Message}  .</li>
    353   <li>    {@link android.os.Message}    {@link
    354 android.os.Handler}&mdash;  ,   {@link android.os.Handler#handleMessage
    355 handleMessage()}.</li>
    356 </ul>
    357 
    358 
    359 <p> ,        .  
    360    ( {@link android.os.Message}),    
    361   {@link android.os.Handler}.</p>
    362 
    363 <p>   ,    {@link android.os.Messenger}:</p>
    364 
    365 <pre>
    366 public class MessengerService extends Service {
    367     /** Command to the service to display a message */
    368     static final int MSG_SAY_HELLO = 1;
    369 
    370     /**
    371      * Handler of incoming messages from clients.
    372      */
    373     class IncomingHandler extends Handler {
    374         &#64;Override
    375         public void handleMessage(Message msg) {
    376             switch (msg.what) {
    377                 case MSG_SAY_HELLO:
    378                     Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
    379                     break;
    380                 default:
    381                     super.handleMessage(msg);
    382             }
    383         }
    384     }
    385 
    386     /**
    387      * Target we publish for clients to send messages to IncomingHandler.
    388      */
    389     final Messenger mMessenger = new Messenger(new IncomingHandler());
    390 
    391     /**
    392      * When binding to the service, we return an interface to our messenger
    393      * for sending messages to the service.
    394      */
    395     &#64;Override
    396     public IBinder onBind(Intent intent) {
    397         Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
    398         return mMessenger.getBinder();
    399     }
    400 }
    401 </pre>
    402 
    403 <p> ,   {@link android.os.Handler#handleMessage handleMessage()}  
    404 {@link android.os.Handler}  ,      {@link android.os.Message}
    405  ,   ,   {@link android.os.Message#what}.</p>
    406 
    407 <p>     {@link android.os.Messenger}    {@link
    408 android.os.IBinder},  ,       {@link
    409 android.os.Messenger#send send()}.    ,      
    410      {@code MSG_SAY_HELLO}:</p>
    411 
    412 <pre>
    413 public class ActivityMessenger extends Activity {
    414     /** Messenger for communicating with the service. */
    415     Messenger mService = null;
    416 
    417     /** Flag indicating whether we have called bind on the service. */
    418     boolean mBound;
    419 
    420     /**
    421      * Class for interacting with the main interface of the service.
    422      */
    423     private ServiceConnection mConnection = new ServiceConnection() {
    424         public void onServiceConnected(ComponentName className, IBinder service) {
    425             // This is called when the connection with the service has been
    426             // established, giving us the object we can use to
    427             // interact with the service.  We are communicating with the
    428             // service using a Messenger, so here we get a client-side
    429             // representation of that from the raw IBinder object.
    430             mService = new Messenger(service);
    431             mBound = true;
    432         }
    433 
    434         public void onServiceDisconnected(ComponentName className) {
    435             // This is called when the connection with the service has been
    436             // unexpectedly disconnected -- that is, its process crashed.
    437             mService = null;
    438             mBound = false;
    439         }
    440     };
    441 
    442     public void sayHello(View v) {
    443         if (!mBound) return;
    444         // Create and send a message to the service, using a supported 'what' value
    445         Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
    446         try {
    447             mService.send(msg);
    448         } catch (RemoteException e) {
    449             e.printStackTrace();
    450         }
    451     }
    452 
    453     &#64;Override
    454     protected void onCreate(Bundle savedInstanceState) {
    455         super.onCreate(savedInstanceState);
    456         setContentView(R.layout.main);
    457     }
    458 
    459     &#64;Override
    460     protected void onStart() {
    461         super.onStart();
    462         // Bind to the service
    463         bindService(new Intent(this, MessengerService.class), mConnection,
    464             Context.BIND_AUTO_CREATE);
    465     }
    466 
    467     &#64;Override
    468     protected void onStop() {
    469         super.onStop();
    470         // Unbind from the service
    471         if (mBound) {
    472             unbindService(mConnection);
    473             mBound = false;
    474         }
    475     }
    476 }
    477 </pre>
    478 
    479 <p> ,      ,    .  ,
    480   ,    {@link android.os.Messenger}   . ,
    481      {@link android.content.ServiceConnection#onServiceConnected
    482 onServiceConnected()},      {@link android.os.Message},   
    483 {@link android.os.Messenger}      {@link android.os.Message#replyTo}
    484  {@link android.os.Messenger#send send()}.</p>
    485 
    486 <p>         <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html">{@code
    487 MessengerService.java}</a> ()  <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html">{@code
    488 MessengerServiceActivities.java}</a> ().</p>
    489 
    490 
    491 
    492 
    493 
    494 <h2 id="Binding">  </h2>
    495 
    496 <p>      ()   
    497 {@link android.content.Context#bindService bindService()}.    Android
    498   {@link android.app.Service#onBind
    499 onBind()} ,    {@link android.os.IBinder}    .</p>
    500 
    501 <p>  . {@link android.content.Context#bindService
    502 bindService()}     <em></em>    
    503 {@link android.os.IBinder}.    {@link android.os.IBinder}     {@link
    504 android.content.ServiceConnection}      {@link android.content.Context#bindService
    505 bindService()}.  {@link android.content.ServiceConnection}    ,
    506     ,    {@link android.os.IBinder}.</p>
    507 
    508 <p class="note"><strong>.</strong>       ,     
    509 &mdash;  <strong> </strong>       .</p>
    510 
    511 <p>           . </p>
    512 <ol>
    513   <li>  {@link android.content.ServiceConnection}.
    514     <p>       :</p>
    515     <dl>
    516       <dt>{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}</dt>
    517         <dd>   ,    {@link android.os.IBinder},  
    518 {@link android.app.Service#onBind onBind()}.</dd>
    519       <dt>{@link android.content.ServiceConnection#onServiceDisconnected
    520 onServiceDisconnected()}</dt>
    521         <dd> Android       
    522   ,           .   <em></em> ,  
    523  .</dd>
    524     </dl>
    525   </li>
    526   <li>  {@link
    527 android.content.Context#bindService bindService()},      {@link
    528 android.content.ServiceConnection}. </li>
    529   <li>       {@link android.content.ServiceConnection#onServiceConnected
    530 onServiceConnected()},          
    531 ,  .</li>
    532   <li>   ,   {@link
    533 android.content.Context#unbindService unbindService()}.
    534     <p>         ,     
    535           ,  
    536    ,    . (        
    537     ).</p>
    538   </li>
    539 </ol>
    540 
    541 <p>            
    542 <a href="#Binder">  Binder</a>      
    543 {@link android.os.IBinder}   {@code LocalService}    {@code
    544 LocalService}:</p>
    545 
    546 <pre>
    547 LocalService mService;
    548 private ServiceConnection mConnection = new ServiceConnection() {
    549     // Called when the connection with the service is established
    550     public void onServiceConnected(ComponentName className, IBinder service) {
    551         // Because we have bound to an explicit
    552         // service that is running in our own process, we can
    553         // cast its IBinder to a concrete class and directly access it.
    554         LocalBinder binder = (LocalBinder) service;
    555         mService = binder.getService();
    556         mBound = true;
    557     }
    558 
    559     // Called when the connection with the service disconnects unexpectedly
    560     public void onServiceDisconnected(ComponentName className) {
    561         Log.e(TAG, "onServiceDisconnected");
    562         mBound = false;
    563     }
    564 };
    565 </pre>
    566 
    567 <p>    {@link android.content.ServiceConnection}      ,   
    568  {@link android.content.Context#bindService bindService()}. :</p>
    569 
    570 <pre>
    571 Intent intent = new Intent(this, LocalService.class);
    572 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    573 </pre>
    574 
    575 <ul>
    576   <li>    {@link android.content.Context#bindService bindService()}   
    577 {@link android.content.Intent},        (   
    578  ).</li>
    579 <li>    {@link android.content.ServiceConnection}.</li>
    580 <li>    ,   .    {@link
    581 android.content.Context#BIND_AUTO_CREATE},  ,     .
    582   : {@link android.content.Context#BIND_DEBUG_UNBIND}
    583  {@link android.content.Context#BIND_NOT_FOREGROUND}  {@code 0},   .</li>
    584 </ul>
    585 
    586 
    587 <h3> </h3>
    588 
    589 <p>        .</p>
    590 <ul>
    591   <li>   {@link android.os.DeadObjectException},  
    592    .   ,    .</li>
    593   <li>        . </li>
    594   <li>        
    595         . :
    596     <ul>
    597       <li>        ,   , 
    598      {@link android.app.Activity#onStart onStart()},        {@link
    599 android.app.Activity#onStop onStop()}.</li>
    600       <li> ,               ,
    601       {@link android.app.Activity#onCreate onCreate()},   
    602      {@link android.app.Activity#onDestroy onDestroy()}.   ,    ,
    603        ,    (      ). ,
    604      ,     ,  
    605   ,    .</li>
    606     </ul>
    607     <p class="note"><strong>.</strong>  <strong></strong>      
    608     {@link android.app.Activity#onResume onResume()}  {@link
    609 android.app.Activity#onPause onPause()}  ,             ,
    610    ,    ,   .  ,      
    611       ,     
    612   ,       ,      
    613 (  )  ,      (  ). (         
    614   
    615 <a href="{@docRoot}guide/components/activities.html#CoordinatingActivities"></a>.)</p>
    616 </ul>
    617 
    618 <p> ,       , .  ,   <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code
    619 RemoteService.java}</a>,  <a href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p>
    620 
    621 
    622 
    623 
    624 
    625 <h2 id="Lifecycle">    </h2>
    626 
    627 <p>       ,  Android    (    
    628   {@link android.app.Service#onStartCommand onStartCommand()}).      
    629     ,     
    630 &mdash;  Android            .</p>
    631 
    632 <p>,        {@link android.app.Service#onStartCommand
    633 onStartCommand()},      ,  
    634     <em></em>.        , 
    635         {@link android.app.Service#stopSelf()}    ,       {@link
    636 android.content.Context#stopService stopService()},      -
    637 .</p>
    638 
    639 <p> ,       ,    
    640   {@link android.app.Service#onUnbind onUnbind()}    
    641 {@code true},      {@link android.app.Service#onRebind
    642 onRebind()}      (     {@link
    643 android.app.Service#onBind onBind()}).  {@link android.app.Service#onRebind
    644 onRebind()}   void,   -   {@link android.os.IBinder}     
    645 {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}.
    646  1       .</p>
    647 
    648 
    649 <img src="{@docRoot}images/fundamentals/service_binding_tree_lifecycle.png" alt="" />
    650 <p class="img-caption"><strong>1.</strong>    ,
    651    .</p>
    652 
    653 
    654 <p>           <a href="{@docRoot}guide/components/services.html#Lifecycle"></a>.</p>
    655 
    656 
    657 
    658 
    659