image.png

Service

Service(服务)是一个后台运行的组件,执行长时间运行且不需要用户交互的任务。即使应用被销毁也依然可以工作。服务的两种启动状态

状态 描述
Started Android的应用程序组件,如活动,通过startService()启动了服务,则服务是Started状态。一旦启动,服务可以在后台无限期运行,即使启动它的组件已经被销毁。
Bound 当Android的应用程序组件通过bindService()绑定了服务,则服务是Bound状态。Bound状态的服务提供了一个客户服务器接口来允许组件与服务进行交互,如发送请求,获取结果,甚至通过IPC来进行跨进程通信。
image.png

要创建服务,需要创建一个继承自Service基类或者它的已知子类的Java类。

Service基类定义了不同的回调方法和多数重要方法。你不需要实现所有的回调方法。

回调 描述
onStartCommand() 其他组件(如活动)通过调用startService()来请求启动服务时,系统调用该方法。如果你实现该方法,你有责任在工作完成时通过stopSelf()或者stopService()方法来停止服务。
onBind() 当其他组件想要通过bindService()来绑定服务时,系统调用该方法。如果你实现该方法,你需要返回IBinder对象来提供一个接口,以便客户来与服务通信。你必须实现该方法,如果你不允许绑定,则直接返回null。
onUnbind() 当客户中断所有服务发布的特殊接口时,系统调用该方法。
onRebind() 当新的客户端与服务连接,且此前它已经通过onUnbind(Intent)通知断开连接时,系统调用该方法。
onCreate() 当服务通过onStartCommand()和onBind()被第一次创建的时候,系统调用该方法。该调用要求执行一次性安装。
onDestroy() 当服务不再有用或者被销毁时,系统调用该方法。你的服务需要实现该方法来清理任何资源,如线程,已注册的监听器,接收器等。

Started方式实战

修改AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.user.service"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><service android:name=".MyService" /></application></manifest>

添加<service android:name=".MyService" />这句话.

增加MyService.java代码:

package com.example.user.service;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;public class MyService extends Service {@Overridepublic IBinder onBind(Intent arg0) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// Let it continue running until it is stopped.Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();return START_STICKY;}@Overridepublic void onDestroy() {super.onDestroy();Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();}
}

修改MainActivity.java代码:

package com.example.user.service;import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}// Method to start the servicepublic void startService(View view) {startService(new Intent(getBaseContext(), MyService.class));}// Method to stop the servicepublic void stopService(View view) {stopService(new Intent(getBaseContext(), MyService.class));}
}

修改activity_main.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="137dp"android:layout_marginTop="57dp"android:layout_marginEnd="159dp"android:layout_marginBottom="253dp"android:onClick="startService"android:text="启动服务"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/button" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="137dp"android:layout_marginTop="105dp"android:layout_marginEnd="159dp"android:layout_marginBottom="57dp"android:onClick="stopService"android:text="停止服务"app:layout_constraintBottom_toTopOf="@+id/button2"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>

运行效果:

image.png

image.png

Bound方式实战

修改AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.user.service"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><serviceandroid:name=".MyService"android:enabled="true"android:exported="true"></service></application></manifest>

创建MyService.java:

package com.example.user.service;import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;public class MyService extends Service {private MyBinder binder = new MyBinder();private int count = 0;public class MyBinder extends Binder{public int getCount(){return count;}}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.Log.d("test","Service onBinder.");return binder;}@Overridepublic void onCreate() {super.onCreate();Log.d("test","Service onCreate.");count++;}@Overridepublic boolean onUnbind(Intent intent){Log.d("test","Service onUnbind");return true;}@Overridepublic void onDestroy(){super.onDestroy();Log.d("test","Service onDestroy");}
}

修改MainActivity.java:

package com.example.user.service;import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {Button b1,b2,getCon;MyService.MyBinder binder;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.d("test","--service connect--");binder = (MyService.MyBinder)service;}@Overridepublic void onServiceDisconnected(ComponentName name) {Log.d("test","--service disconnect--");}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);b1 = (Button) findViewById(R.id.button1);b2 = (Button) findViewById(R.id.button2);getCon = (Button) findViewById(R.id.button3);final Intent intent = new Intent(this, MyService.class);b1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {bindService(intent, conn, Service.BIND_AUTO_CREATE);}});b2.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {unbindService(conn);}});getCon.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(MainActivity.this,"count:"+binder.getCount(),Toast.LENGTH_SHORT).show();}});}
}

修改activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="148dp"android:layout_marginTop="77dp"android:layout_marginEnd="148dp"android:layout_marginBottom="95dp"android:text="start"app:layout_constraintBottom_toTopOf="@+id/button2"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="148dp"android:layout_marginTop="95dp"android:layout_marginEnd="148dp"android:layout_marginBottom="243dp"android:text="stop"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/button1" /><Buttonandroid:id="@+id/button3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="148dp"android:layout_marginTop="78dp"android:layout_marginEnd="148dp"android:layout_marginBottom="85dp"android:text="GetStatus"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/button2" />
</android.support.constraint.ConstraintLayout>

执行结果:

image.png

2020-06-28 16:36:15.052 8758-8758/com.example.user.service D/test: Service onCreate.
2020-06-28 16:36:15.054 8758-8758/com.example.user.service D/test: Service onBinder.
2020-06-28 16:36:15.056 8758-8758/com.example.user.service D/test: --service connect--
2020-06-28 16:36:40.249 8758-8780/com.example.user.service D/EGL_emulation: eglMakeCurrent: 0xebc57240: ver 2 0 (tinfo 0xebc036c0)
2020-06-28 16:36:40.257 8758-8780/com.example.user.service D/EGL_emulation: eglMakeCurrent: 0xebc57240: ver 2 0 (tinfo 0xebc036c0)
2020-06-28 16:37:27.518 8758-8758/com.example.user.service D/test: Service onUnbind
2020-06-28 16:37:27.518 8758-8758/com.example.user.service D/test: Service onDestroy

http://www.taodudu.cc/news/show-6789382.html

相关文章:

  • PuyoPuyo(DFS算法)
  • Linux中断系列之中断或异常处理(四)
  • 光度色度学基础及其在LED照明中的应用
  • 色度学基础(二)
  • 【色度学】光度学基础
  • 打开任务管理器,不小心关闭了windows资源管理器,桌面不见了
  • 撒的发撒范德萨
  • vue实现全屏只显示内容不显示导航条和退出全屏调用事件
  • mysql5.7 终端无法输入中文数据库不能输入中文的解决方法
  • 萨达撒啊速度撒
  • java桌球游戏
  • 苹果笔记本安装双系统(Windows10)思路
  • macOS是不是计算机系统,苹果笔记本的MAC和OSX系统 有什么不同。还是二种系统是一样的。现在和的苹果笔记本电脑何种系统。...
  • 苹果M1芯片笔记本电脑SIP系统完整性保护无法关闭成功
  • c语言怎么实现电梯控制系统设计,基于单片机的电梯控制系统设计.doc
  • 基于单片机的电梯程序控制系统(仿真+程序+测试视频)
  • cvs add: added independently by second party 问题解决
  • 使用Go Fiber构建微服务
  • 什么?你学深度学习还不会预测房价:回归问题?我来教你
  • 软件系统扩展性_我如何将软件系统的性能扩展35,000%
  • 美团面试,问了ThreadLocal原理,这个回答让我通过了
  • 论文分享-->Independently Recurrent Neural Network (IndRNN): Building A Longer and Deeper RNN
  • cvs added independently by second party Error, CVS operation failed
  • 跟我学Kafka之Controller控制器详解(一)
  • 用Python写《我的世界》(MC)
  • 用python写一个我的世界
  • Pygame实战:方块连接世界,云游大好河山—《我的世界》已上线,确定不进来康康嘛?
  • 用Python写《我的世界》
  • [python]比较文章相似度
  • 相似度图片搜索原理

Android Service启动相关推荐

  1. 一篇文章看明白 Android Service 启动过程

    Android - Service 启动过程 相关系列 一篇文章看明白 Android 系统启动时都干了什么 一篇文章了解相见恨晚的 Android Binder 进程间通讯机制 一篇文章看明白 An ...

  2. Android service 启动篇之 startService

    系列博文: Android 中service 详解 Android service 启动篇之 startService Android service 启动篇之 bindService Android ...

  3. Android Service启动到Activity

    飞哥语录:心怀希望,就会充满力量! 从Service启动到Activity基本可以分为两类: 1.从自己应用的Service启动自己应用的Activity,即显式意图: 2.从自己应用的Service ...

  4. android启动服务的生命周期,android Service启动运行服务 生命周期

    Service Android中的service类似于windows中的service,service一般没有用户操作界面,它运行于系统中不容易被用户发觉, 可以使用它开发如监控之类的程序. 一.步骤 ...

  5. Android Service: 启动service, 停止service

    [ 启动service ] 1. 定义Service类 2. 在manifest中注册 3. 在activity中启动 1. 定义Service类 @Override public IBinder o ...

  6. Android service启动流程分析.

    文章仅仅用于个人的学习记录,基本上内容都是网上各个大神的杰作,此处摘录过来以自己的理解学习方式记录一下. 参考链接: https://my.oschina.net/youranhongcha/blog ...

  7. android组件启动,Android四大组件Service之StartService启动

    对于Service两种方式在概述里已经介绍了,下面是学习是StartService的代码实例. service启动代码: package com.example.service01; import a ...

  8. android服务的启动过程,Android Service的启动过程(上)

    原标题:Android Service的启动过程(上) (点击上方公众号,可快速关注) 来源:伯乐在线专栏作者 - xuyinhuan 链接:http://android.jobbole.com/85 ...

  9. service启动activity_「 Android 10 四大组件 」系列—Service 的 quot; 启动流程 quot;

    作者:DeepCoder 核心源码 关键类路径 Service 的启动过程相对 Activity 的启动过程来说简单了很多,我们都知道怎么去创建和启动一个 Service, 那么你有没有从源码角度研究 ...

最新文章

  1. ATMEGA8 DIP-28面包板实验
  2. 如何设计秒杀服务器的限流策略
  3. error: No resource identifier found for attribute ‘backIcon’ in package
  4. 【MySQL经典案例分析】关于数据行溢出由浅至深的探讨
  5. C#语言使用多态(接口与override) ——帮您剔除对面向对象多态性的疑惑
  6. python查询缺失值所在位置_Python Pandas找到缺失值的位置方法
  7. mysql删除记录后id不连续_小水玩转Mysql---Mysql跟踪sql记录
  8. 1005 地球人口承载力估计
  9. 爬取外网数据(twitter、facebook)-易数云可视化爬虫软件
  10. java 车牌模糊_免费模糊车牌照片处理软件
  11. 3.SPSS Modeler数据基本分析笔记
  12. 任正非:管理上的灰色,是我们的生命之树
  13. android 手机 报证书错误,安卓 ssl证书 安卓ssl证书出现错误的可能原因? - SSL网...
  14. 以物理弦理论的角度浅理解悖论
  15. python 画图 平滑曲线_用Python平滑曲线
  16. mysql 去除逗号,MySQL查询删除字符串中最后一个逗号后的所有字符?
  17. python版亲戚关系计算器
  18. 虹科ELPRO的智能数据记录仪由Sensirion技术驱动
  19. crm登录功能实现记住我
  20. 生活随记 - 立冬 暖阳高照

热门文章

  1. 常用的Essay写作句型怎么详细分析?
  2. esxi做文件服务器拒绝,VMware ESXi和ESX “lsassd”服务远程拒绝服务漏洞
  3. wps云文档本地服务器,wps账户登录云存储服务器
  4. Android中ListView的优化
  5. 怎么将电脑桌面上dwg格式图纸进行打开查看?
  6. spark和shark
  7. 现代计算机网络的发展,现代计算机网络发展-东南大学学报.pdf
  8. python机器人编程——在VREP环境中,UARM与摄像头联动,实现基于视觉识别的自动抓取,垃圾自动分类(上)
  9. 如何搭建大学生搜题公众号?
  10. iconfont 使用方法