Service使用方法

service生命周期

启动Service
startService();
1. 启动 onCreate——onStartCommand——onStart
2. 再一次启动 onStartCommand——onStart

销毁Service
onDestroy

一、首先,让我们确认下什么是service?
service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互、它必须由用户或者其他程序显式的启动、它的优先级比较高,它比处于前台的应用优先级低,但是比后台的其他应用优先级高,这就决定了当系统因为缺少内存而销毁某些没被利用的资源时,它被销毁的概率很小哦。
二、那么,什么时候,我们需要使用service呢?
我们知道,service是运行在后台的应用,对于用户来说失去了被关注的焦点。这就跟我们打开了音乐播放之后,便想去看看图片,这时候我们还不想音乐停止,这里就会用到service;又例如,我们打开了一个下载链接之后,我们肯定不想瞪着眼睛等他下载完再去做别的事情,对吧?这时候如果我们想手机一边在后台下载,一边可以让我去看看新闻啥的,就要用到service。
三、service分类:
一般我们认为service分为两类,本地service和远程service。
本地service顾名思义,那就是和当前应用在同一个进程中的service,彼此之间拥有共同的内存区域,所以对于某些数据的共享特别的方便和简单;
远程service:主要牵扯到不同进程间的service访问。因为android的系统安全的原因导致了我们在不同的进程间无法使用一般的方式共享数据。在这里android为我们提供了一个AIDL工具。(android interface description language)android接口描述语言。
四、service生命周期:
和Activity相比,service的生命周期已经简单的不能再简单了,只有onCreate()->onStart()->onDestroy()三个方法。
Activity中和service有关的方法:
startService(Intent intent):启动一个service
stopService(Intent intent) :停止一个service
如果我们想使用service中的一些数据或者访问其中的一些方法,那么我们就要通过下面的方法:
public boolean bindService(Intent intent, ServiceConnection conn, int flags) ;
public void unbindService(ServiceConnection conn);
intent是跳转到service的intent,如 Intent intent = new Intent(); intent.setClass(this,MyService.class);
conn则是一个代表与service连接状态的类,当我们连接service成功或失败时,会主动触发其内部的onServiceConnected或onServiceDisconnected方法。如果我们想要访问service中的数据,可以在onServiceConnected()方法中进行实现,

五、ANDROID中BINDSERVICE的使用方法
bindService用于绑定一个服务。这样当bindService(intent,conn,flags)后,就会绑定一个服务。这样做可以获得这个服务对象本身,而用startService(intent)的方法只能启动服务。

bindService方式的一般过程:

①新建Service类BindService。在BindService类里新建内部类MyBinder,继承自Binder(Binder实现IBinder接口)。MyBinder提供方法返回BindService实例。

public class MyBinder extends Binder{

    public BindService getService(){
        return BindService.this;
    }
}

实例化MyBinder得到mybinder对象;

重写onBind()方法:

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

②在Activity里,实例化ServiceConnection接口的实现类,重写onServiceConnected()和onServiceDisconnected()方法

ServiceConnection conn=new ServiceConnection(){

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}

@Override
public void onServiceDisconnected(ComponentName name) {
}

};

③在Activity的onCreate()方法里,新建Intent,并绑定服务

    Intent intent=new Intent(MainActivity.this,BindService.class); 
    bindService(intent, conn,BIND_AUTO_CREATE);

④在Activity的onDestroy里面,添加

unbindService(conn);

如果不加这一步,就会报android.app.ServiceConnectionLeaked: **.MainActivity has leaked ServiceConnection的异常。

bindService()的执行过程如下:

bindService(intent,conn,flag)->Service:onCreate()->Service:onBind()->Activity:onServiceConnected()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值