Android中Service(二)

Android安卓进程保活()设置前台Service 其它文章首先你要知道Android中的进程以及它的优先级,下面来说明它进程前台进程 (Foreground process)可见进程 (Visible process)服务进程 (Service process)后台进程 (Background process)空进程 (Empty process) 阅读详情

Service是Android中四大组件之一,在Android开发中起到非常重要的作用,先来看一下官方对Service的定义:

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

翻译过来就是:Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

Service有两种状态,“启动的”和“绑定”

Started

A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

Bound

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

通过startService()启动的服务处于“启动的”状态,一旦启动,service就在后台运行,即使启动它的应用组件已经被销毁了。通常started状态的service执行单任务并且不反悔任何结果给启动者。比如当下载或上传一个文件,当这项操作完成时,service应该停止它本身。

还有一种“绑定”状态的service,通过调用bindService()来启动,一个绑定的service提供一个允许组件与service交互的接口,可以发送请求、获取返回结果,还可以通过夸进程通信来交互(IPC)。绑定的service只有当应用组件绑定后才能运行,多个组件可以绑定一个service,当调用unbind()方法时,这个service就会被销毁了。

另外,在官方的说明文档中还有一个警告:

Caution: 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). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

意思是service与activity一样都存在与当前进程的主线程中,所以,一些阻塞UI的操作,比如耗时操作不能放在service里进行,比如另外开启一个线程来处理诸如网络请求的耗时操作。如果在service里进行一些耗CPU和耗时操作,可能会引发ANR警告,这时应用会弹出是强制关闭还是等待的对话框。所以,对service的理解就是和activity平级的,只不过是看不见的,在后台运行的一个组件,这也是为什么和activity同被说为Android的基本组件。

Service生命周期中的一些方法:


通过这个图可以看到,两种启动service的方式以及他们的声明周期,bind service的不同之处在于当绑定的组件销毁后,对应的service也就被kill了。service的声明周期相比与activity的简单了许多,只要好好理解两种启动service方式的异同就行。

service生命周期也涉及一些回调方法,这些方法都不用调用父类方法,具体如下:

  1. public class ExampleService extends Service {  
  2.     int mStartMode;       // indicates how to behave if the service is killed   
  3.     IBinder mBinder;      // interface for clients that bind   
  4.     boolean mAllowRebind; // indicates whether onRebind should be used   
  5.   
  6.     @Override  
  7.     public void onCreate() {  
  8.         // The service is being created   
  9.     }  
  10.     @Override  
  11.     public int onStartCommand(Intent intent, int flags, int startId) {  
  12.         // The service is starting, due to a call to startService()   
  13.         return mStartMode;  
  14.     }  
  15.     @Override  
  16.     public IBinder onBind(Intent intent) {  
  17.         // A client is binding to the service with bindService()   
  18.         return mBinder;  
  19.     }  
  20.     @Override  
  21.     public boolean onUnbind(Intent intent) {  
  22.         // All clients have unbound with unbindService()   
  23.         return mAllowRebind;  
  24.     }  
  25.     @Override  
  26.     public void onRebind(Intent intent) {  
  27.         // A client is binding to the service with bindService(),   
  28.         // after onUnbind() has already been called   
  29.     }  
  30.     @Override  
  31.     public void onDestroy() {  
  32.         // The service is no longer used and is being destroyed   
  33.     }  
  34. }<
  35. 关于Service生命周期还有一张比较易懂的图(来源于网络)


    另外,这里要说明Service的一个子类,IntentService,首先看下官方文档的说明:

    IntentService

    This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.

    IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。而在一般的继承Service里面如果要进行耗时操作就必须另开线程,但是使用IntentService就可以直接在里面进行耗时操作,因为默认实现了一个worker thread。对于异步的startService请求,IntentService会处理完成一个之后再处理第二个。

    看下IntentService的具体实现:

    1. public class HelloIntentService extends IntentService {  
    2.   
    3.   /**  
    4.    * A constructor is required, and must call the super IntentService(String) 
    5.    * constructor with a name for the worker thread. 
    6.    */  
    7.   public HelloIntentService() {  
    8.       super("HelloIntentService");  
    9.   }  
    10.   
    11.   /** 
    12.    * The IntentService calls this method from the default worker thread with 
    13.    * the intent that started the service. When this method returns, IntentService 
    14.    * stops the service, as appropriate. 
    15.    */  
    16.   @Override  
    17.   protected void onHandleIntent(Intent intent) {  
    18.       // Normally we would do some work here, like download a file.   
    19.       // For our sample, we just sleep for 5 seconds.   
    20.       long endTime = System.currentTimeMillis() + 5*1000;  
    21.       while (System.currentTimeMillis() < endTime) {  
    22.           synchronized (this) {  
    23.               try {  
    24.                   wait(endTime - System.currentTimeMillis());  
    25.               } catch (Exception e) {  
    26.               }  
    27.           }  
    28.       }  
    29.   }  
    30. }

    关于停止Service,如果service是非绑定的,最终当任务完成时,为了节省系统资源,一定要停止service,可以通过stopSelf()来停止,也可以在其他组件中通过stopService()来停止,绑定的service可以通过onUnBind()来停止service。

    关于Service还有很多知识,这里就不再一一列举,可以参考 http://developer.android.com/guide/components/services.html


Android安卓进程保活()设置前台Service(1) 外链图片转存中…(img-75zoInyl-1712218296787)] 阅读详情

相关推荐

Android安卓进程保活()设置前台Service(1),万字解析

都说三年是程序员的一个坎,能否晋升或者提高自己的核心竞争力,这几年就十分关键。技术发展的这么快,从哪些方面开始学习,才能达到高级工程师水平,最后进阶到Android架构师/技术专家?我总结了这 5大块;我搜集整理过这几年阿里,以及腾讯,字节跳动,华为,小米等公司的面试题,把面试的要求和技术点梳理成一份大而全的“ Android架构师”面试 PDF(实际上比预期多花了不少精力),包含知识脉络 + 分支细节。Java语言与原理;大厂,小厂。Android面试先看你熟不熟悉Java语言高级UI与自定义view。

m0_75011249的博客 1695

安卓Service

一.Service有几种启动方式 Service种启动方式,一种就是我上次写的startService,另一种是bindService。下面将主要介绍bindService以及IntentService(一种新的类,并不是启动方式)。 .startService的特点及优缺点 优点:startService使用简单,和Activity一样,只要几行代码就能启动Service。 缺点:...

qq_41451851的博客 298

Android安卓进程保活()设置前台Service,已获千赞

现在新技术层出不穷,如果每次出新的技术,我们都深入的研究的话,很容易分散精力。新的技术可能很久之后我们才会在工作中用得上,当学的新技术无法学以致用,很容易被我们遗忘,到最后真的需要使用的时候,又要从头来过(虽然上手会更快)。我觉得身为技术人,针对新技术应该是持拥抱态度的,入了这一行你就应该知道这是一个活到老学到老的行业,所以面对新技术,不要抵触,拥抱变化就好了。Flutter 明显是一种全新的技术,而对于这个新技术在发布之初,花一个月的时间学习它,成本确实过高。

2401_84153079的博客 934

安卓核心组件service

安卓核心组件service 简介:服务是能够在后台长时间运行操作并且不提供用户界面的应用程序组件,例如,服务能在后台处理网络服务,播放音乐,执行文件IO或者与CotentService通信 service的分类 started(启动):启动服务启动后在后台无限期运行,即使启动服务的组件已经销毁; bound(绑定):绑定服务提供客户端-服务端接口,以允许组件与服务交互,发送请求,获得结果,甚至使

lucky_eyefocus的博客 574

安卓service使用(

安卓service使用(

motosheep的博客 609

我的安卓记录service

service在后台运行 生命周期:onCreate()–>onStart()–>onDestroy() 1、新建一个service类package com.example.wlb.launchlocalapp;import android.app.Service; import android.content.Intent; import android.os.Binder; import a

a761185074的博客 274

android登录service,Android Service详解()第一个Service

Service中有四个重要函数:publicIBinderonBind(Intentarg0);//必须实现,返回接口给ServicepublicvoidonCreate();//Service创建时调用publicvoidonStart(Intentintent,intstartId);//通过startService()会调用publi...

weixin_26833139的博客 230

android service 弹出,AndroidService中弹出对话框

上一篇我也写了一篇弹窗的,但是经过测试,Android8.0之后用不了,所以改一下Myservice.classpackage com.nf.service;import android.app.AlertDialog;import android.app.AliasActivity;import android.app.Dialog;import android.app.Service;impo...

weixin_39710966的博客 360

Android开发学习之Service详解

1.先讲讲怎么使用bindService()绑定服务     应用组件(客户端)可以调用bindService()绑定到一个serviceAndroid系统之后调用service的onBind()方法,它返回一个用来与service交互的IBinder   绑定是异步的.bindService()会立即返回,它不会返回IBinder给客户端.要接收IBinder,客户端必须创建一个S

逍遥飞鹤的专栏 2549

深入分析 Android Service ()

在后台执行长时间运行的操作,并提供多种机制来管理其生命周期和性能。无论是简单的异步任务,还是复杂的前台服务,通过合理设计和优化。,结合具体需求进行优化,是构建高效、稳定的 Android 应用的重要一环。我们将实现一个下载管理服务,它可以在后台下载文件,并在下载完成后通知用户。通过启动前台服务,我们确保服务在系统资源紧张时不会被杀死。,系统将尝试重新创建服务,但不传递最后的。,系统将尝试重新创建服务,并传递最后一个。方法被调用,服务将一直运行,直到调用。,以及在设计和实现中需要注意的事项。

结合项目案例,记录点点滴滴,自己回顾,分享他人o__o 9454

Android Service 服务 BroadcastReceiver

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 一、 Broadcas

dghggij的博客 546
上一篇: android service(一)
下一篇: android getLastKnownLocation 返回null
CYoung
博客等级 码龄15年 25粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值