Android传感器入门

Android Service 的启动停止及其绑定

2017-05-09  本文已影响143人  b7cda9616c52

销毁服务

本篇文章将销毁服务放在第一位,是因为销毁服务很重要,也因为在后面的描述中会经常提到销毁服务。
在服务完成任务后必须进行销毁,否则一直占用资源,导致内存溢出。
判断服务销毁的标志是,服务的 onDestroy() 方法执行了。

销毁服务的方式

使用 Context 的 startService 启动

Intent intent = new Intent(MainActivity.this, LifecycleService.class);
startService(intent);

启动前台服务

启动服务的方式与上面的 startService 相同,只是在 Service 的 onStartCommand 里使用startForeground()方法将服务变为前台服务并创建通知,如下:

startForeground(startId, NotificationUtil.createNotification(this));

NotificationUtil 是我自己写的一个创建通知的工具类。

使用 Context 的 bindService 绑定服务

绑定 Service 后,可以与 Service 之间进行通信。绑定方式如下:

bindService(new Intent(MainActivity.this, LifecycleService.class), mServiceConnection,
                  Context.BIND_AUTO_CREATE);

mServiceConnection用于界面和 Service 的连接。

private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override public void onServiceConnected(ComponentName name, IBinder service) {
      Timber.e("onServiceConnected");
      if (service instanceof LifecycleService.MyBinder) {
        mBound = true;
        LifecycleService.MyBinder binder = (LifecycleService.MyBinder) service;
        mLifecycleService = binder.getService();
      }
    }

    @Override public void onServiceDisconnected(ComponentName name) {
      Timber.e("onServiceDisconnected");
      mBound = false;
    }
  };

onServiceConnected方法表示连接成功,然后从其中获取Binder,在 Binder 中定义了一个方法用于获取 Service,这样就可以直接调用 Service 里的方法了。Binder在 Service中实现的,如下。

private final IBinder mBinder = new MyBinder();

  public class MyBinder extends Binder {
    LifecycleService getService() {
      return LifecycleService.this;
    }
  }

  @Override public IBinder onBind(Intent intent) {
    return mBinder;
  }

这里的onBind的返回值是不能返回 null 的。若返回 null,不会回调 onServiceConnected 方法,也不能销毁服务。

官方文档说了:为了确保应用的安全性,请始终使用显式 Intent 启动或绑定 Service,且不要为服务声明 Intent 过滤器。

上一篇 下一篇

猜你喜欢

热点阅读