Service 的两种启动方法和区别
- 格式:doc
- 大小:17.50 KB
- 文档页数:1
service的启动⽅式⾸先简单的说说,activity和service之间关系1,Activity 和 Service 都是 Android 四⼤组件之⼀,他俩都是Context 类的⼦类 ContextWrapper 的⼦类,因此他俩可以算是兄弟关系吧!2,Activity负责⽤户界⾯的显⽰和交互,Service 负责后台任务的处理。
Activity 和 Service 之间可以通过 Intent 传递数据,因此可以把 Intent 看作是通信使者.3,对于同⼀个app,activity和service都是在主线程中.(⼩知识:service中可以吐司的)...service的启动⽅式 1,startservice 2,bindservice1,采⽤start的⽅式开启服务⾸先定义⼀个类继承service,在注册清单中配置service(四⼤组件都应该注册!),使⽤context中的startService(Intent)⽅法启动该Service.不使⽤时,调⽤stopService(Intent)⽅法停⽌该服务.⼀旦服务开启跟调⽤者(开启者)就没有任何关系了。
开启者退出了,开启者挂了,服务还在后台长期的运⾏。
开启者不能调⽤服务⾥⾯的⽅法。
2,采⽤bind的⽅式开启服务 ⾸先定义⼀个类继承service,在注册清单中配置service,使⽤Contex t的bindService(Intent, ServiceConnection, int)⽅法启动该Service,不再使⽤时,调⽤unbindService(ServiceConnection)⽅法停⽌该服务.bind的⽅式开启服务,绑定服务,调⽤者挂了,服务也会跟着挂掉。
绑定者可以调⽤服务⾥⾯的⽅法。
startservice和bindservice的使用场景下载温馨提示:该文档是我店铺精心编制而成,希望大家下载以后,能够帮助大家解决实际的问题。
文档下载后可定制随意修改,请根据实际需要进行相应的调整和使用,谢谢!并且,本店铺为大家提供各种各样类型的实用资料,如教育随笔、日记赏析、句子摘抄、古诗大全、经典美文、话题作文、工作总结、词语解析、文案摘录、其他资料等等,如想了解不同资料格式和写法,敬请关注!Download tips: This document is carefully compiled by the editor. I hope that after you download them, they can help you solve practical problems. The document can be customized and modified after downloading, please adjust and use it according to actual needs, thank you!In addition, our shop provides you with various types of practical materials, such as educational essays, diary appreciation, sentence excerpts, ancient poems, classic articles, topic composition, work summary, word parsing, copy excerpts, other materials and so on, want to know different data formats and writing methods, please pay attention!Android中的服务组件是一种非常重要的组件,它可以在后台执行长时间运行的操作,而不会阻塞应用的主线程。
service的用法总结大全(学习版)编制人:__________________审核人:__________________审批人:__________________编制学校:__________________编制时间:____年____月____日序言下载提示:该文档是本店铺精心编制而成的,希望大家下载后,能够帮助大家解决实际问题。
文档下载后可定制修改,请根据实际需要进行调整和使用,谢谢!并且,本店铺为大家提供各种类型的经典范文,如英语单词、英语语法、英语听力、英语知识点、语文知识点、文言文、数学公式、数学知识点、作文大全、其他资料等等,想了解不同范文格式和写法,敬请关注!Download tips: This document is carefully compiled by this editor.I hope that after you download it, it can help you solve practical problems. The document can be customized and modified after downloading, please adjust and use it according to actual needs, thank you!In addition, this shop provides various types of classic sample essays, such as English words, English grammar, English listening, English knowledge points, Chinese knowledge points, classical Chinese, mathematical formulas, mathematics knowledge points, composition books, other materials, etc. Learn about the different formats and writing styles of sample essays, so stay tuned!service的用法总结大全service的意思n. 服务,服侍,服务业,维修服务,服役vt. 检修,维修,向…提供服务,保养,满足需要adj. 服务性的,耐用的,服现役的变形:过去式: serviced;现在分词:servicing;过去分词:serviced;service用法service可以用作名词service作名词的基本意思是“服务”,可指商店、旅馆或餐馆对顾客、旅客的服务,也可指社会等公益事业服务机构为人们所提供的服务,还可指某人为别人〔社会、政府〕所采取的行动、工作或帮助。
Android Service 两种启动方式的区别最近在debug android service destory的bug,网上找了service相关的知识,startservice和bindservice都可以启动service,知道这两种方式的区别还是很有作用的。
Android Service 生命周期可以促使移动设备的创新,让用户体验到最优越的移动服务,只有broadcast receivers执行此方法的时候才是激活的,当onReceive()返回的时候,它就是非激活状态。
如果没有程序停止它或者它自己停止,service将一直运行。
在这种模式下,service开始于调用Context.start Service() ,停止于Context.stop Service(). service可以通过调用Android Service 生命周期() 或Service.stopSelfResult()停止自己。
不管调用多少次start Service() ,只需要调用一次stop Service() 就可以停止service。
可以通过接口被外部程序调用。
外部程序建立到service的连接,通过连接来操作service。
建立连接调开始于Context.bind Service(), 结束于Context.unbind Service(). 多个客户端可以绑定到同一个service,如果service没有启动,bind Service() 可以选择启动它。
服务不能自己运行,需要通过调用Context.startService()或Context.bindService()方法启动服务。
这两个方法都可以启动Service,但是它们的使用场合有所不同。
使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。
使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止,大有“不求同时生,必须同时死”的特点。
Android中bindService的使用及Service生命周期Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context 的bindService方法,本文只探讨纯bindService的使用,不涉及任何startService方法调用的情况。
bindService启动服务的特点相比于用startService启动的Service,bindService启动的服务具有如下特点:1. bindService启动的服务在调用者和服务之间是典型的client-server的接口,即调用者是客户端,service是服务端,service就一个,但是连接绑定到service上面的客户端client可以是一个或多个。
这里特别要说明的是,这里所提到的client指的是组件,比如某个Activity。
2. 客户端client(即调用bindService的一方,比如某个Activity)可以通过IBinder接口获取Service的实例,从而可以实现在client端直接调用Service中的方法以实现灵活的交互,并且可借助IBinder实现跨进程的client-server的交互,这在纯startService启动的Service中是无法实现的。
3. 不同于startService启动的服务默认无限期执行(可以通过Context的stopService或Service 的stopSelf方法停止运行),bindService启动的服务的生命周期与其绑定的client息息相关。
当client销毁的时候,client会自动与Service解除绑定,当然client也可以通过明确调用Context的unbindService方法与Service解除绑定。
当没有任何client与Service绑定的时候,Service会自行销毁(通过startService启动的除外)。
配置服务的命令serviceservice和systemctl服务化开机启动实践:1)vim /lib/systemd/system/WebSvc.service[Unit]Description=WebSvc service[Service]Type=forkingRemainAfterExit=noExecStart=/bin/sh /home/testWebSvc/systemctWebSvc.sh[Install]WantedBy=multi-user.targetCMDsystemctl enable WebSvc;Created symlink from /etc/systemd/system/multi-user.target.wants/WebSvc.service to /lib/systemd/system/WebSvc.service.#!/bin/bashsleep 1s/usr/bin/nohup /home/test/WebSvc -conf /home/test/WebSvc/configs/config.yaml > /dev/null 2>&1 &systemctl --helpsystemctl [OPTIONS...] {COMMAND} ...Query or send control commands to the systemd manager.-h --help Show this help--version Show package version--system Connect to system manager--user Connect to user service manager-H --host=[USER@]HOSTOperate on remote host-M --machine=CONTAINEROperate on local container-t --type=TYPE List units of a particular type--state=STATE List units with particular LOAD or SUB or ACTIVE state-p --property=NAME Show only properties by this name-a --all Show all loaded units/properties, including dead/emptyones. To list all units installed on the system, usethe 'list-unit-files' command instead.-l --full Don't ellipsize unit names on output-r --recursive Show unit list of host and local containers--reverse Show reverse dependencies with 'list-dependencies'--job-mode=MODE Specify how to deal with already queued jobs, whenqueueing a new job--show-types When showing sockets, explicitly show their type-i --ignore-inhibitorsWhen shutting down or sleeping, ignore inhibitors--kill-who=WHO Who to send signal to-s --signal=SIGNAL Which signal to send--now Start or stop unit in addition to enabling or disabling it-q --quiet Suppress output--no-block Do not wait until operation finished--no-wall Don't send wall message before halt/power-off/reboot--no-reload Don't reload daemon after en-/dis-abling unit files--no-legend Do not print a legend (column headers and hints)--no-pager Do not pipe output into a pager--no-ask-passwordDo not ask for system passwords--global Enable/disable unit files globally--runtime Enable unit files only temporarily until next reboot-f --force When enabling unit files, override existing symlinksWhen shutting down, execute action immediately--preset-mode= Apply only enable, only disable, or all presets--root=PATH Enable unit files in the specified root directory-n --lines=INTEGER Number of journal entries to show-o --output=STRING Change journal output mode (short, short-iso,short-precise, short-monotonic, verbose,export, json, json-pretty, json-sse, cat)--firmware-setup Tell the firmware to show the setup menu on next boot--plain Print unit dependencies as a list instead of a treelines 27-49--kill-who=WHO Who to send signal to-s --signal=SIGNAL Which signal to send--now Start or stop unit in addition to enabling or disabling it-q --quiet Suppress output--no-block Do not wait until operation finished--no-wall Don't send wall message before halt/power-off/reboot--no-reload Don't reload daemon after en-/dis-abling unit files--no-legend Do not print a legend (column headers and hints)--no-pager Do not pipe output into a pager--no-ask-passwordDo not ask for system passwords--global Enable/disable unit files globally--runtime Enable unit files only temporarily until next reboot-f --force When enabling unit files, override existing symlinksWhen shutting down, execute action immediately--preset-mode= Apply only enable, only disable, or all presets--root=PATH Enable unit files in the specified root directory-n --lines=INTEGER Number of journal entries to show-o --output=STRING Change journal output mode (short, short-iso,short-precise, short-monotonic, verbose,export, json, json-pretty, json-sse, cat)--firmware-setup Tell the firmware to show the setup menu on next boot --plain Print unit dependencies as a list instead of a treeUnit Commands:list-units [PATTERN...] List loaded unitslist-sockets [PATTERN...] List loaded sockets ordered by addresslist-timers [PATTERN...] List loaded timers ordered by next elapsestart NAME... Start (activate) one or more unitsstop NAME... Stop (deactivate) one or more unitsreload NAME... Reload one or more unitsrestart NAME... Start or restart one or more unitstry-restart NAME... Restart one or more units if activereload-or-restart NAME... Reload one or more units if possible, otherwise start or restarttry-reload-or-restart NAME... If active, reload one or more units,if supported, otherwise restartisolate NAME Start one unit and stop all otherskill NAME... Send signal to processes of a unitis-active PATTERN... Check whether units are activeis-failed PATTERN... Check whether units are failedstatus [PATTERN...|PID...] Show runtime status of one or more units show [PATTERN...|JOB...] Show properties of one or moreunits/jobs or the managercat PATTERN... Show files and drop-ins of one or more unitsset-property NAME ASSIGNMENT... Sets one or more properties of a unit help PATTERN...|PID... Show manual for one or more unitsreset-failed [PATTERN...] Reset failed state for all, one, or moreunitslist-dependencies [NAME] Recursively show units which are requiredor wanted by this unit or by which thisunit is required or wantedUnit File Commands:list-unit-files [PATTERN...] List installed unit filesenable NAME... Enable one or more unit filesdisable NAME... Disable one or more unit filesreenable NAME... Reenable one or more unit filespreset NAME... Enable/disable one or more unit filesbased on preset configurationpreset-all Enable/disable all unit files based onpreset configurationis-enabled NAME... Check whether unit files are enabledmask NAME... Mask one or more unitsunmask NAME... Unmask one or more unitslink PATH... Link one or more units files intothe search pathadd-wants TARGET NAME... Add 'Wants' dependency for the targeton specified one or more unitsadd-requires TARGET NAME... Add 'Requires' dependency for the target on specified one or more unitsedit NAME... Edit one or more unit filesget-default Get the name of the default targetset-default NAME Set the default targetMachine Commands:list-machines [PATTERN...] List local containers and hostJob Commands:list-jobs [PATTERN...] List jobscancel [JOB...] Cancel all, one, or more jobsEnvironment Commands:show-environment Dump environmentset-environment NAME=VALUE... Set one or more environment variables unset-environment NAME... Unset one or more environment variablesimport-environment [NAME...] Import all or some environment variablesManager Lifecycle Commands:daemon-reload Reload systemd manager configurationdaemon-reexec Reexecute systemd managerSystem Commands:is-system-running Check whether system is fully runningdefault Enter system default moderescue Enter system rescue modeemergency Enter system emergency modehalt Shut down and halt the systempoweroff Shut down and power-off the systemreboot [ARG] Shut down and reboot the systemkexec Shut down and reboot the system with kexecexit [EXIT_CODE] Request user instance or container exitswitch-root ROOT [INIT] Change to a different root file systemsuspend Suspend the systemhibernate Hibernate the systemhybrid-sleep Hibernate and suspend the systemlines 91-132/132 (END)systemctl开机启动设置_龙哥哥的博客-CSDN博客_systemctl 开机启动 https:///tl4832194/article/details/109781230常⽤的systemctl命令以sshd服务为例,列出常⽤systemctl命令:启动sshd服务:systemctl start ssh.service停⽌sshd服务:systemctl stop ssh.service查看sshd服务状态:systemctl status ssh.service重启sshd服务:systemctl restart ssh.service设置开机⾃启动:systemctl enable ssh.service禁⽌开机⾃启动:systemctl disable ssh.service查看所有已经启动的服务:systemctl list-units --type=service重新加载配置⽂件:systemctl daemon-reloadsystemctl启动服务编写Centos7的服务systemctl脚本存放在:/usr/lib/systemd/⽬录下,有系统(system)和⽤户(user)之分,⼀般需要开机不登录就能运⾏的程序,就存放在/usr/lib/systemd/system/⽬录下每⼀个服务以.service结尾,⼀般会分为3部分:[Unit]、[Service]和[Install],以sshd为实例如下:[Unit]Description=OpenSSH server daemonDocumentation=man:sshd(8) man:sshd_config(5)After=network.target sshd-keygen.serviceWants=sshd-keygen.service[Service]Type=notifyEnvironmentFile=/etc/sysconfig/sshdExecStart=/usr/sbin/sshd -D $OPTIONSExecReload=/bin/kill -HUP $MAINPIDKillMode=processRestart=on-failureRestartSec=42s[Install]WantedBy=multi-user.target[Unit]部分主要是对这个服务的说明,内容包括Description和After,Description ⽤于描述服务,After⽤于描述服务类别;[Service]部分是服务的关键,是服务的⼀些具体运⾏参数的设置;[Install]部分是服务安装的相关设置,可设置为多⽤户的;配置⽂件详解UnitAfter 表⽰服务需要在***服务启动之后执⾏⽆依赖Before 表⽰服务需要在***服务启动之前执⾏⽆依赖Wants 弱依赖关系Requires 强依赖关系 ***停⽌之后本服务也必须停⽌ServiceExecStart 启动进程时执⾏的命令ExecReload 重启服务时执⾏的命令ExecStop 停⽌服务时执⾏的命令ExecStartPre 启动服务之前执⾏的命令ExecStartPost 启动服务之后执⾏的命令ExecStopPost 停⽌服务之后执⾏的命令所有的启动设置之前,都可以加上⼀个连词号(-),表⽰"抑制错误", 即发⽣错误的时候,不影响其他命令的执⾏。
调用service服务方法调用service服务•介绍•方法一:直接调用•方法二:使用Intent启动Service•方法三:使用Messenger进行进程间通信•方法四:使用AIDL实现跨进程通信•总结介绍在Android开发中,我们常常需要使用service服务来完成一些后台任务。
调用service服务可以让我们的应用变得更加强大和灵活。
本文将介绍几种常用的调用service服务的方法。
方法一:直接调用最简单的调用service服务的方法是直接调用其提供的方法。
首先,我们需要在文件中声明service组件,然后通过()方法来启动服务。
接下来,我们可以通过获取service实例来直接调用其方法。
// 启动serviceIntent intent = new Intent(context, );(intent);// 获取service实例并调用其方法MyService service = new MyService();();方法二:使用Intent启动Service除了直接调用service,我们还可以通过使用Intent来启动service。
这种方法更加灵活,可以方便地传递数据给service。
// 启动service并传递数据Intent intent = new Intent(context, );("key", value);(intent);在service的onStartCommand()方法中,我们可以通过Intent 获取传递的数据。
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {if(intent != null) {String value = ("key");// 处理传递的数据}// 其他逻辑...}方法三:使用Messenger进行进程间通信有时候我们需要在不同的进程间进行通信,可以使用Messenger 实现。
Service知识点整理Service简单概述Service(服务)是一个一种可以在后台执行长时间运行操作而没有用户界面的应用组件。
服务可由其他应用组件启动(如Activity),服务一旦被启动将在后台一直运行,即使启动服务的组件(Activity)已销毁也不受影响。
此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信(IPC)。
例如,服务可以处理网络事物、播放音乐、执行文件I/O或与内容提供程序交互,而这一切均可在后台进行。
Service基本上分为两种形式:启动当应用组件(如Activity)通过调用startService()启动服务时,服务即处于“启动”状态。
一旦启动,服务即可在后台无限期运行,即使启动服务的组件已被销毁也不受影响。
已启动的服务通常是执行单一操作,而且不会将结果返回给调用方。
例如,它可能通过网络下载或上传文件。
操作完成后,服务会自动停止运行。
绑定当应用组件通过调用bindService()绑定到服务时,服务即处于“绑定”状态。
绑定的服务提供了一个客户端-服务器接口,允许组件与服务进行交互、发送请求、获取结果,甚至是利用线程间通信(IPC)跨进程执行这些操作。
仅当与另一个应用组件绑定时,绑定服务才会运行。
多个组件也可以同时绑定到该服务,单全部取消绑定后,该服务即会被销毁。
无论应用处于启动状态还是绑定状态,抑或处于启动并且绑定状态,任何应用组件均可像使用Activity那样通过调用Intent来使用服务(即使此服务来自另外一个应用)。
不过,可以通过清单文件将服务声明为私有服务,并阻止其他应用访问。
基础知识通过创建Service子类(或使用它的一个现有子类)来创建服务。
在现实中,需要重写一些回调方法,已处理服务生命周期的某些关键方面并提供一种机制将组件绑定到服务。
onStartCommand()当另一个组件(如Activity)通过调用startService()请求启动服务时,系统将调用此方法。