一.Service启动方式介绍
Service有两种启动方式,无论哪种启动方式,都需要
- 定义一个类继承Service
- 在清单文件中配置该Service
1、startService()开启服务:
使用Context的startService()开启服务,所对应的生命周期为:
2、bind开启服务
使用Context的bindService()开启服务,所对应的生命周期为:
和绑定者有关系,开启者挂掉,服务也会挂掉;
绑定着可调用服务里的方法;
二.如何调用Service里的方法(只限bind开启服务)
第一步:自定义一个接口,用于保护服务中的不想被外界访问的方法
public interface InterfaceMyBinder { void protectMethodInMyService(); }
第二步:自定义一个类继承service
public class MyService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { //返回自定义MyBinder对象 return new MyBinder(); } /** * 可被绑定者调用的服务里的方法 */ private void MyServicemethod() { Toast.makeText(getApplicationContext(), "调用服务里的方法了!!!!", Toast.LENGTH_SHORT).show(); } /** * 创建一个内部类 提供一个方法,可以间接调用服务的方法 */ private class MyBinder extends Binder implements InterfaceMyBinder { @Override public void protectMethodInMyService() { MyServicemethod(); } } }
第三步:在清单文件配置MyService
<service android:name=".service.MyService"/>
第四步:绑定服务的activity
开启服务方法:
//开启服务 private Intent intent; private MyServiceConn myServiceConn; public void startservice() { intent = new Intent(this, MyService.class); myServiceConn = new MyServiceConn(); //绑定服务(intent对象,绑定服务的监听器,一般为BIND_AUTO_CREATE常量) bindService(intent, myServiceConn, BIND_AUTO_CREATE); }
创建内部类实现ServiceConnection()
private class MyServiceConn implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder iBinder) { //iBinder为服务里面onBind()方法返回的对象,所以可以强转为自定义InterfaceMyBinder类型 myBinder = (InterfaceMyBinder) iBinder; } @Override public void onServiceDisconnected(ComponentName name) { } }
调用服务里的方法:
public void getServiceMethod() { myBinder.protectMethodInMyService(); }