在Android开发过程中,Android API 已经有了startService方式,为什么还需要bindService呢?
答:是因为bindService可以实现Activity-->Service里面的方法并返回数据给Activity,可以理解 在自身APP过程中Service与Activity进行通讯(本地服务)
bindService还可以实现另外强大的功能,需要结合AIDL,实现跨进程Service与Activity进行通讯(远程服务)
定义接口来增强服务返回到Binder:
package liudeli.service1.service.inter; import liudeli.service1.service.domain.Person; public interface IPerson { /** * 通过ID查询Person对象 * @param id */ public Person queryPersonByID(int id); }
服务处理onBind方法:
package liudeli.service1.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import liudeli.service1.service.domain.Person; import liudeli.service1.service.inter.IPerson; public class MyService3 extends Service { @Override public IBinder onBind(Intent intent) { return new MyBinder(); } class MyBinder extends Binder implements IPerson { /** * 通过ID查询Person对象 * * @param id */ @Override public Person queryPersonByID(int id) { Person person = null; switch (id) { case 1: person = new Person(1, "张三", 30); break; case 2: person = new Person(2, "李四", 20); break; case 3: person = new Person(3, "赵六", 26); break; default: person = new Person(9,"王五", 40); break; } return person; } } }
MainActivity3调用服务到方法:
package liudeli.service1; 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.util.Log; import android.view.View; import liudeli.service1.service.MyService3; import liudeli.service1.service.inter.IPerson; public class MainActivity3 extends Activity { private final static String TAG = MainActivity3.class.getSimpleName(); private MyServiceConnection connection = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); connection = new MyServiceConnection(); } public void bindService(View view) { bindService(new Intent(this, MyService3.class), connection, BIND_AUTO_CREATE); } public void unBindService(View view) { unbindService(connection); } private IPerson person = null; /** * 服务连接接口具体实现对象 */ class MyServiceConnection implements ServiceConnection { /** * 与服务进行连接 * @param name * @param service */ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d("MyService3", "与服务进行连接 name:" + name); person = (IPerson) service; } /** * 与服务断开连接 * @param name */ @Override public void onServiceDisconnected(ComponentName name) { person = null; System.gc(); } } @Override protected void onDestroy() { super.onDestroy(); if (null != connection) { unbindService(connection); } } public void testMothod(View view) { if (null != person) { liudeli.service1.service.domain.Person p = person.queryPersonByID(1); Log.d("MyService3", "p.toString" + p.toString()); } } }