Service Android

本文深入解析Android中的Service组件,包括其概念、应用场景、启动方式及生命周期等。特别关注Service如何处理后台任务,以及如何通过Intent与Activity进行通信。

导读:
一共分为三部分:
第一部分:Service简介和基础使用
第二部分:Service的生命周期
第三部分:前台Service

Service简介和基础使用

我这里不过多讲解Service的基础只是稍微提一点重要的内容。

  • Service是什么?是android四大组件之一,适合用于耗时的后台任务。是没有UI界面的,可以使用Service更新Contentprovider等等任务。
  • Service不是什么?不是一个独立的进程。不是一个独立的线程。
    如果使用了Service本身是存在于线程之中的,Service阻塞之后会阻塞所在线程,一些耗时的任务需要在Service之中再开一些线程来处理。
  • Service开发时遇到的问题汇总
    Service中socket会崩溃:这是因为Service如果所在线程是主线程也就是UI线程的话,在UI线程调用socket是会导致崩溃的。

Service注册

<service android:name="com.feather.socketservice.IHomeService">
</service>

Service类实现

继承Service

public class IHomeService extends Service{
    //实现一些方法
}

Service的使用

/*绑定service, 利用connection建立与service的联系*/
  Intent serviceIntent = new Intent();
  serviceIntent.putExtra("command", "auth");//通过intent传递值给Service
  serviceIntent.setClass(ClientActivity.this, IHomeService.class);
  //bindService(serviceIntent, connection, BIND_AUTO_CREATE); //绑定service,并且自动创建service
  startService(serviceIntent); //开启服务,第一次会调用onCreate方法和onStartCommand方法。第二次之后就只调用onStartCommand方法

startService(serviceIntent);第一次会调用onCreate方法和onStartCommand方法。第二次之后就只调用onStartCommand方法。
* activity和service通信通过广播和intent进行。

Service的使用

public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        if(intent != null) //有时候系统会自动重启Service所以Intent有时候可能是为null的,所以要先判断,防止出现崩溃的问题。
        {
            ;   
        }
        return super.onStartCommand(intent, flags, startId);
    }

Service的生命周期

请直接参考链接:生命周期讲解-博客园

前台Service

相关内容甚至详细内容可以参考大牛的文章:http://blog.youkuaiyun.com/guolin_blog/article/details/11952435

总结

Service分类

1、按启动方式分类:

1、StartService
step:
— 1、继承Service类并实现自己的服务
public class MyService extends Service {}

— 2、在AndroidMainfest中注册
<service android:name="com.example.demo.service.MyService" > </service>

— 3、启动服务startService(Intent)
在onStartCommand()中实现具体的业务

— 4、停止服务stopService(Intent)和stopSelf()

2、BoundService

2.服务性质

— Local Service
— Remote Service

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值