温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android基础(五) – Service生命周期及启动方式

发布时间:2020-07-05 16:34:58 来源:网络 阅读:446 作者:lm8751 栏目:移动开发

继承关系

Context -> ContextWrapper -> Service 位于 android.app 包中

Service的生命周期

Service启动

1.StartService 同一个Service Start多次,onCreate()执行一次,onStartCommand()执行多次

2.BindService 同一个Service bind多次, onCreate()执行一次,onBind()也执行一次

注意:

1.启动也分隐式和显式.但考虑到安全等因数,如果不是也许需求 一般我们使用显示的调用方式。

2.onStartCommand(Intent intent, int flags, int startId)

onStartCommand有4种返回值

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。

START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

3.BindService例代码

Service部分

private BindServiceX myBinderServiceX=new BindServiceX();
public class BindServiceX extends Binder{
public BindService getBindService() {
return BindService.this;
}
}

@Override
public IBinder onBind(Intent arg0) {
    // 此处返回自定义Binder
    return myBinderServiceX;
}

组件调用部分(以Activity为例)

Intent intentBind = new Intent(AndroidServiceActivity.this, BindService.class);
bindService(intentBind,
new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        //Service对外提供Bind
       BindServiceX bindServiceX = (BindServiceX) service;
       //通过bind提供的方法得到Service引用
       BindService bindService = bindServiceX.getBindService();
       //todo 接下来可以和Service通信了

    }
};

, Context.BIND_AUTO_CREATE);

Service关闭

1.stopSelf();

2.stopSelfResult();

3.stopService()

注意:

1.同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用(调用顺序无所谓),才能终止 Service.

2.Service哪种方式启动必须调用与之对应方法才会关闭Service。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI