Android基础 —— Service使用

本文详细介绍了Android中的Service,包括Service的简单实用、两种启动方式、生命周期及其不同情况下的变化,以及如何让Service自动重启。还探讨了在AndroidManifest.xml中配置Service、使用bindService启动Service的方法,强调了不同启动方式对Service生命周期的影响。
摘要由CSDN通过智能技术生成

Android中的服务和windows中的服务是类似的东西,服务一般没有用户操作界面,它运行于系统中不容易被用户发觉,可以使用它开发如监控之类的程序 。

Service 的简单实用
  1. 第一步:继承Service类
public class MyService extends Service {
    }
  1. 第二步:在AndroidManifest.xml文件中的节点里对服务进行配置:
<service android:name=".MyService" />


  1. 第三部:Service 启动方式

  • 启动:Context.startService(Intent service)
  • 停止:Context.stopService(Intent name)
  • 启动:Context.bindService(Intent service, ServiceConnection conn,
    int flags)
  • 停止:Context.unbindService(ServiceConnection conn)
Service 的两种启动方式
  • 隐式启动:
    首先在 AndroidManifest.xml 清单文件中对 service 进行配置:
    <service android:name=".MyService" android:exported="true">
        <intent-filter>
            <action android:name="com.cfox.myservice"/>
        </intent-filter>
</service>

从代码中可以看到在 service 中有 android:exported,并且我们设置成了 true ,如果设置成 true 则表示可以通过其他App 启动该服务,如果设置为false 不可被外部应用启动(默认为false),如果设置了 intent-filter 则android:exported将默认设置为true。再看这个几行配置代码,在service 中添加了 intent-filter ,又在 intent-filter 中添加 action。看到这可能会有疑问,action 是干什么的?下面我们来看一下隐式启动方式

Intent intent = new Intent();
intent.setAction("com.cfox.myservice");
intent.setPackage("com.cfox.servicecontrol");
startService(intent);

我们可以看到在 Intent 中设置了 Action,并且 Action 的内容和 AndroidManifest.xml 中 intent-filter 中的 action 相对应。可到这里可能明白些了,继续看 setPackage 就又不明白了,启动service 为什么还要 setPackage ,在Android 5.0 开始如果你不设置 setPackage 将无法启动 service 同时还会抛出异常。下面我们来看一下 Android 4.4 和 Android 5.0 启动 service 的源码。

Android 4.4

    @Override
    public ComponentName startService(Intent service) {
        warnIfCallingFromSystemProcess();
        return startServiceCommon(service, mUser);
    }
    private ComponentName startServiceCommon(Intent service, UserHandle user) {
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值