导读:
一共分为三部分:
第一部分: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
本文深入解析Android中的Service组件,包括其概念、应用场景、启动方式及生命周期等。特别关注Service如何处理后台任务,以及如何通过Intent与Activity进行通信。
1万+

被折叠的 条评论
为什么被折叠?



