Android Service 浅析

这篇博客用如下的结构来讲解Service:


1.先看一下Service是什么。

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

Service 是一个能够在后台执行长时间运行的操作并且不提供用户界面的应用程序组件。Service是Android的四大组件(其实我更喜欢叫他们“四大金刚”)之一。


2.开始一直认为Service运行在后台其他线程里面的组件,后来发现错了。答案就在下面这句话中:

A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise)。

Service 运行在主进程中的主线程(也就是人们经常说的UI线程)里面,Service 不创建自己的线程,同样也不运在一个单独的进程(区别于Service所在的应用程序的进程)(除非你指定)。


3.我特别喜欢洋毛子写的文章或者文档,特别严谨。先说Service的定义,也就是Service是什么,然后说Service不是什么(1.A Service is not a separate process. Service不是一个单独的进程。 2.A Service is not a thread. Service不是一个线程。),这样正反两方面就能很好地理解Service的基本概念了。


4.说完Service的基本概念,那就该说什么时候使用Service。  Service什么时候使用也没有明确定义,但是可以根据Service的特性可以推断出来,比如说可以在后台执行,MP3音乐播放那一块可以用Service实现,比如说可以长时间地执行某种操作,上传和下载文件可以用Service实现,等等。


5.那现在是时候讲解Service的生命周期了,有些时候图片比文字更能说清楚一个问题。Service的生命周期如下:

The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService().

图左边显示的是用startService创建的Service的生命周期,图右边显示的是bindService创建的Service的生命周期。

这个图中还给我们指出Service 的创建有两种方式 1.startService() 方式。 2.bindService() 方式。


6. Service 的代码实例如下:

     6.1 Service如果在App中使用,创建一个类继承Service类或者Service的子类。

     6.2 在manifest文件中声明这个Service,例如 <service android:name=".MyService"></service>

     6.3.1 startService方式启动 MyService重写 onStartCommand()方法,如下:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    用startService(new Intent(this,MyService.class));来启动Service,用stopService(new Intent(this,MyService.class))来停止Service。

    6.3.2 bindService 方式启动 MyService重写 onStartCommand()方法。

    用bindService();来启动Service,用unBindService()来停止Service。




本人就是一个Android小菜鸟,如有错误,请您包涵指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值