Android学习_Service

来源:互联网 发布:大数据自学 编辑:程序博客网 时间:2024/05/02 04:40

description: 从官方的文档就可以看出Service应用程序的模块之一,当应用程序需要去做一些需要长时间运行的操作(后台处理一些耗时的逻辑),并且不需要与用户进行交互,这个时候就可以用Service来在后台实现。

最近又开始重新折腾起Android开发,之前赶项目的时候简单地做过一个Android应用,现在的话又要重新学起了…不废话了。

概述

public abstract class

Service

extends ContextWrapper

implements ComponentCallbacks2

A Service is an application component representing either an application’s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package’s AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

从官方的文档就可以看出Service应用程序的模块之一,当应用程序需要去做一些需要长时间运行的操作(后台处理一些耗时的逻辑),并且不需要与用户进行交互,这个时候就可以用Service来在后台实现。

那么总结一下Service的特点

  • 后台运行,通常是应用的一个功能模块;
  • 通常是长时间运行的逻辑操作,即使程序退出的情况下,依然可以让Service在后台保持运行状态;
  • 不需要和用户进行交互;
  • 在整个应用程序中都是通用的;
  • 运行在主线程,因此不能用来做耗时的请求或操作(可以在服务里新开一个线程)。

Service的分类

通常把Service分为两类:

  • 本地服务:Local Service用于应用程序内部,通过调用Context.startService()启动,调用Context.stopService()结束。在内部可以调用Service.stopSelf()来自己停止。无论调用了多少次startService(),只需要调用一次stopService()来停止。
  • 远程服务:Remote Service用于系统内部的应用程序之间,可以定义接口以便进行其他的操作。客户端建立到服务对象的连接,并通过那个连接来调用服务。调用Context.bindService()方法建立连接并启动,调用Context.unbindService()关闭连接。

Service的生命周期

Service只继承了onCreate()onStartCommand()onDestroy()三个方法,第一次启动Service的时候,先后调用了onCreate()、onStartCommand()这两个方法,当停止Service时,则执行onDestory()方法,而当我们的Service已经启动的时候,再次启动就直接执行onStartCommand()方法(去手机的应用程序管理器可以查看自己的Service是否处于运行状态)。

Service的使用

通常的用法就是用Intent启动Service,重写父类的onCreate()、onStartCommand()和onDestroy()方法。

Service与Activity的通信

可以在Activity中启动一个service,那么如何让两者之间建立通信关系呢,这里写一部分伪代码。

public class MyService extends Service {    public static final String M_TAG = "MyService";    private MyBinder m_binder = new MyBinder();    @Override    public void onCreate() {        super.onCreate();        Log.i(M_TAG, "onCreate() executed");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i(M_TAG, "onStartCommand() executed");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        Log.i(M_TAG, "onDestroy() executed");    }    @Override    public IBinder onBind(Intent intent) {        return m_binder;    }    class MyBinder extends Binder {        public void MyMethod() {            Log.i(M_TAG, "Start MyMethod()");            // ...        }    }}

启动一个Service实际上是开启一个新的进程,那么Service和Activity之间的通信实际上就是不同进程间的通信问题(暂时不多叙述)。上面的代码用到了IBinder,这是个什么样的东西呢?

public interface

IBinder

Base interface for a remotable object, the core part of a lightweight remote procedure call mechanism designed for high performance when performing in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. Do not implement this interface directly, instead extend from Binder.

IBinder是远程对象的一个基本接口,一个为进程和跨进程调用服务的轻量级的远程调用机制的核心部分,该接口描述了一个抽象的协议。上述的伪代码中实现了一个自定义的MyBinder方法,在其中加入了自己的MyMethod方法。

接下来,修改启动MyService的MainActivity:

public class MainActivity extends Activity {    // ...    private MyService.MyBinder m_binder;    private ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            m_binder = (MyService.MyBinder)service;            m_binder.MyMethod();        }        @Override        public void onServiceDisconnected(ComponentName name, IBinder service) {            // ..        }    };    // ...}

public interface

ServiceConnection

Interface for monitoring the state of an application service. Like many callbacks from the system, the methods on this class are called from the main thread of your process.

这里创建了一个匿名的类ServiceConnection,重写了onServiceConnected和onServiceDisconnection方法,这两个方法会在Activity与Service建立和解除connection的时候调用。然后通过IBinder接口,Activity就可以调用Service内部的方法。

当然两者的绑定还需要调用bindService(Intent, ServiceConnection, int)接口,这里第三个参数int是一个标志位。

  • BIND_ALLOW_OOM_MANAGEMENT:allow the process hosting the bound service to go through its normal memory management.
  • BIND_AUTO_CREATE:automatically create the service as long as the binding exists.
  • BIND_DEBUG_UNBIND: include debugging help for mismatched calls to unbind.
  • BIND_IMPORTANT:this service is very important to the client, so should be brought to the foreground process level when the client is.
  • BIND_NOT_FOREGROUND:don’t allow this binding to raise the target service’s process to the foreground scheduling priority.
  • BIND_WAIVE_PRIORITY:don’t impact the scheduling or memory management priority of the target service’s hosting process.

解除两者之间的connection只需要调用unbindService(connection)接口即可。

当然Service不仅可以和建立它的Activity之间建立connection,和应用程序内的其他Activity也是可以建立connection的,并且可以获取相同的extends IBinder的实例。

持续更新…

haha

0 0
原创粉丝点击