android-学习篇-Service(服务)

2024-05-03 20:38
文章标签 android service 学习 服务

本文主要是介绍android-学习篇-Service(服务),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 简介
  • Service
  • 生命周期
  • 启动与绑定方法
  • 创建 Service
  • IntentService
  • 前台服务
  • 参考

简介

Service 是一种可在后台执行长时间运行操作而不提供界面的应用组件。

Service 两种工作状态:

  • 启动状态,主要用于执行后台计算。startService()
  • 绑定状态,主要用于其他组件和 Service 的交互。bindService()

Service

Service 是适用于所有服务的基类。扩展此类时,您必须创建用于执行所有服务工作的新线程,因为服务默认使用应用的主线程,这会降低应用正在运行的任何 Activity 的性能。

package android.app;
public abstract class Service extends ContextWrapper implements ComponentCallbacks2

方法介绍:

// 首次创建服务时,系统会(在调用 onStartCommand() 或 onBind() 之前)调用此方法来执行一次性设置程序。如果服务已在运行,则不会调用此方法。
public void onCreate() 
// 当不再使用服务且准备将其销毁时,系统会调用此方法。服务应通过实现此方法来清理任何资源,如线程、注册的侦听器、接收器等。
public void onDestroy()// 当另一个组件(如 Activity)请求启动服务时,系统会通过调用 startService() 来调用此方法。
int onStartCommand(Intent intent, @StartArgFlags int flags, int startId)
// 当另一个组件想要与服务绑定(例如执行 RPC)时,系统会通过调用 bindService() 来调用此方法。
public abstract IBinder onBind(Intent intent);// 停止服务。此外,其他组件也可通过调用 stopService() 来停止此服务
public final void stopSelf()// 开启前台服务
public final void startForeground(int id, Notification notification)
// 从前台移除服务。此方法采用布尔值,指示是否需同时移除状态栏通知。此方法不会停止服务。但是,如果您在服务仍运行于前台时将其停止,则通知也会随之移除。
public final void stopForeground(boolean removeNotification)

生命周期

public class ExampleService extends Service {int startMode;       // indicates how to behave if the service is killedIBinder binder;      // interface for clients that bindboolean allowRebind; // indicates whether onRebind should be used@Overridepublic void onCreate() {// The service is being created}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// The service is starting, due to a call to startService()return mStartMode;}@Overridepublic IBinder onBind(Intent intent) {// A client is binding to the service with bindService()return mBinder;}@Overridepublic boolean onUnbind(Intent intent) {// All clients have unbound with unbindService()return mAllowRebind;}@Overridepublic void onRebind(Intent intent) {// A client is binding to the service with bindService(),// after onUnbind() has already been called}@Overridepublic void onDestroy() {// The service is no longer used and is being destroyed}
}

无论所有服务是通过 startService() 还是 bindService() 创建,系统均会为其调用 onCreate() 和 onDestroy() 方法。

启动与绑定方法

package android.content;
public class ContextWrapper extends Context public ComponentName startService(Intent service)
public boolean bindService(Intent service, ServiceConnection conn, int flags)

创建 Service

  1. 自定义类继承 Service
  2. 清单文件中注册服务

IntentService

IntentService 是 Service 的子类,其使用工作线程逐一处理所有启动请求。如果您不要求服务同时处理多个请求,此类为最佳选择。实现 onHandleIntent(),该方法会接收每个启动请求的 Intent,以便您执行后台工作。

前台服务

前台服务是用户主动意识到的一种服务,因此在内存不足时,系统也不会考虑将其终止。前台服务必须为状态栏提供通知,将其放在运行中的标题下方。这意味着除非将服务停止或从前台移除,否则不能清除该通知。

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, notificationIntent, 0);Notification notification =new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE).setContentTitle(getText(R.string.notification_title)).setContentText(getText(R.string.notification_message)).setSmallIcon(R.drawable.icon).setContentIntent(pendingIntent).setTicker(getText(R.string.ticker_text)).build();// 注意:提供给 startForeground() 的整型 ID 不得为 0。
startForeground(ONGOING_NOTIFICATION_ID, notification);

参考

  • Android开发者

这篇关于android-学习篇-Service(服务)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/957599

相关文章

2、swift学习-创建基本的控件

与OC想比较而已,其实用swift创建一些基本控件的方法都是一样的,一些基本的属性都是大同小异,只是语法稍稍不同而已,对于刚刚由OC开始学习swift的可能有点不太习惯,但是没关系,多写多练自然而然就会顺手的。 一、用swift创建一个UILabel func createLabel() {         let label = UILabel (frame: CGRect

1、swift学习-字典的基本使用

1、创建一个字典          var dic:Dictionary<String,String> = ["三国演艺":"罗贯中","水浒传":"施耐庵","红楼梦":"曹雪芹","西游记":"吴承恩"]; 2、打印字典的值     println(dic);     结果如下图:      3、访问字典中某一个键值     var

Swift学习 字符串的操作 2022年11月更新

Swift 字符串的使用 Swift 字符串是一系列字符的集合。例如 “Hello, World!” 这样的有序的字符类型的值的集合,它的数据类型为 String 一、基本使用 1.1字符串的拼接 let str1 = "Hello"let str2 = "World"let str3 = str1 + str2print(str3); 1.2 字符串的插入 for index

iOS 学习资源

一、个人博客 1、刚刚在线 2、浅谈iOS开发中方法延迟执行的几种方式 3、MBProgressHUD 4、MJRefresh 5、AFNetworking 6、iOS数据持久化 7、iOS微信支付 二、常用的开发平台地址 1、银联支付开发平台

SpringBoot 学习六:数据库的增删改查

1、新建一个Girl类,添加如下代码: package controlle;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class Girl {@Id@GeneratedValueprivate Integer

SpringBoot 学习五:连接数据库

1、在pom.xml需要添加与数据库相关的两个依赖: <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>my

SpringBoot 学习四:macOS安装MySQL 以及报错解决

从MySQL官网下载Mysql,在本地安装好之后,用数据库连接工具Sequl Pro去连接数据库,发现报错了,报错信息有两种: Error1:Unable to connect to host 127.0.0.1 because access was denied.Double-check your username and password and ensure that access fro

SpringBoot 学习三:Controller的使用

1、给同一个类添加两个访问地址 在浏览器里输入: localhost:8081/hello 或者 localhost:8081/hi都能访问到。 2、给整个类指定一个URL  通过设置@RequestMapping("/hello"),给整个类指定一个URL  这个时候就需要通过http://localhost:8081/hello/hi去访问这个类了。 3、如何处理url中的参

SpringBoot 学习二:项目属性配置

默认配置的端口是8080,但是有时候8080端口会被系统其他程序占用,所以我们最好配置一个不常用的端口。 1、配置端口 在resources目录下新建一个application.yml文件 打开applicationl.yml文件,里面是空白的,在里面添加端口: server:port: 8081 重新运行一下程序,在浏览器里面将端口号改成8081,能访问成功,则说明设置生效了。

SpringBoot 学习一:创建第一个工程

1、pom.xml 添加依赖 <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.or