Service是能够在后台长期运行并且不提供用户界面的应用程序组件。
Service可以分为以下两种类型:
public class HelloIntentService extends IntentService { public HelloIntentService() { super("HelloIntentService"); // TODO Auto-generated constructor stub } @Override protected void onHandleIntent(Intent arg0) { // TODO Auto-generated method stub // do something } }
public class HelloService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub return START_STICKY; } }
绑定服务是允许其他应用进程绑定并且与之交互的Service类实现类。为了提供绑定,开发人员必须实现onBind()回调方法。该方法返回IBinder对象,它定义了客户端与服务的交互接口
在实现绑定服务时,最重要的是定义onBind()回调方法返回的接口
(1)继承Binder类:继承Binder类创建接口,从onBind()返回一个实例。仅用于私有应用程序
(2)使用Messenger:它是执行IPC最简单的方式
(3)使用AIDL:不推荐。会导致更加复杂的实现
package com.example.bindertime; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.text.format.Time; public class CurrentTimeService extends Service { public class LocalBinder extends Binder { CurrentTimeService getService(){ //返回当前Service实例 return CurrentTimeService.this; } } private final IBinder binder = new LocalBinder(); @Override public IBinder onBind(Intent intent) { //返回binder实例,自动生成的 // TODO Auto-generated method stub return binder; } public String getCurrentTime(){ Time time = new Time(); time.setToNow(); String currentTime = time.format("%Y-%m-%d %H:%M:%S"); return currentTime; } }
调用bindService()方法,传递ServiceConnection实现
package com.example.bindertime; import com.example.bindertime.CurrentTimeService.LocalBinder; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class CurrentTimeActivity extends Activity { CurrentTimeService cts; boolean bound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); Button button = (Button)findViewById(R.id.current); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(CurrentTimeActivity.this, CurrentTimeService.class); bindService(intent, sc, BIND_AUTO_CREATE); //调用bindService()方法,传递ServiceConnection实现 if(bound){ Toast.makeText(CurrentTimeActivity.this, cts.getCurrentTime(), Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); if(bound){ bound = false; unbindService(sc); } } //实现ServiceConnection,这需要重写onServiceConnected()和onServiceDisconnected()两个回调函数 private ServiceConnection sc = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { //接受Binder实例 // TODO Auto-generated method stub LocalBinder binder = (LocalBinder)service; cts = binder.getService(); bound = true; } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub bound = false; } }; }
package com.example.messengertime; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.text.format.Time; import android.widget.Toast; public class CurrentTimeService extends Service { public class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { //服务在Handler的handleMessage()方法接受message // TODO Auto-generated method stub if(msg.what == CURRENT_TIME){ Time time = new Time(); time.setToNow(); String currentTime = time.format("%Y-%m-%d %H:%M:%S"); Toast.makeText(CurrentTimeService.this, currentTime, Toast.LENGTH_SHORT).show(); }else{ super.handleMessage(msg); } } } public static final int CURRENT_TIME = 0; @Override //Messenger创建IBinder,服务从onBind()方法返回到客户端 public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Messenger messenger = new Messenger(new IncomingHandler());//Handler用于创建Messenger对象 return messenger.getBinder(); } }
package com.example.messengertime; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.view.View; import android.widget.Button; public class CurrentTimeActivity extends Activity { Messenger messenger; boolean bound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); Button button = (Button)findViewById(R.id.current); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(CurrentTimeActivity.this, CurrentTimeService.class); bindService(intent, connection, BIND_AUTO_CREATE); if(bound){ Message message = Message.obtain(null, CurrentTimeService.CURRENT_TIME, 0, 0); try { messenger.send(message); } catch (RemoteException e) { e.printStackTrace(); } } } }); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); if(bound){ bound = false; unbindService(connection); } } private ServiceConnection connection = new ServiceConnection(){ @Override //客户端使用IBinder来实例化Messenger,然后使用它来发送Message对象到服务 public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub messenger = new Messenger(service); bound = true; } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub messenger = null; bound = false; } }; }
可参考这篇文章:service生命周期