Android学习笔记 —— 十四、关于Service的基础使用

一、创建Service

自定义类继承Service类,并在AndroidManifest中注册:

<application >
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />
</application>

自定义Service常用的重写方法以及作用:

方法名 作用
onCreate 服务创建时调用
onStartCommand 服务启动时调用
onDestory 服务销毁时调用
onBind 用于Service和Activity之间的通信,让Activity可以控制运行中的Service

启动和停止Service:

    Intent startIntent = new Intent(this, MyService.class);
    startService(startIntent);

    Intent stopIntent = new Intent(this, MyService.class);
    stopService(stopIntent);

或者可以在Service中通过调用stopSelf();方法来停止该服务


二、Activity和Service进行通信的方法

虽然说onBind方法用于和service进行通信,但是单纯只是onBind方法是无法完成这个功能的。

基本的通信构建过程:

  1. 在自定义的Service类中自定义一个Binder内部类,并获取一个自定义内部类的对象。自定义类中的方法将会在Activity中调用,即这个Service提供给Activity的控制方法都需要在这里书写。而在这里获取到的自定义类对象将作为onBind方法的返回值,在Activity和Service绑定时作为参数之一传入到onServiceConnected方法中。
    //获取一个自定义类对象作为oonBind方法的返回值
    private DownloadBinder mBinder = new DownloadBinder()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值