Android的Service应用程序组件基本编写方法
发布时间:2023-12-17 04:22:00
Service是什么
Service是一个android 系统中的应用程序组件,它跟Activity的级别差不多,但是他没有图形化界面,不能自己运行,只能后台运行,并且可以和其他组件进行交互如更新ContentProvider,Intent以及系统的通知等等。其启动方式有两种:context.startService() 和 context.bindService()。Service通常用来处理一些耗时比较长的操作。
Service的编写
创建一个类(这里为FirstService)继承android.app.Service,并覆盖以下方法:
onBind(Intent intent) Return the communication channel to the service.
onCreate() Called by the system when the service is first created.
onStartCommand(Intent intent, int flags, int startId) Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request.
onDestroy() Called by the system to notify a Service that it is no longer used and is being removed.
AndroidManifest.xml文件中添加service配置
<service android:name=".FirstService"></service>
在Activity中启动和停止Service的点击事件的编写
class StartServiceListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
startService(intent);
}
}
class StopServiceListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
stopService(intent);
}
}


猜你喜欢
- java -jar设置添加启动参数方法java -jar 参数前后位置说明springboot项目启动的时候可以直接使用java -jar
- 1.上原图 前几天在 Hencoder 征稿看到的Filpboard 里的的动画效果:Filipboard.gif先bb一句:在看本文的同时
- 本文实例为大家分享了C语言实现扫雷游戏的具体代码,供大家参考,具体内容如下前言一、游戏规则介绍扫雷是一个十分经典的游戏,一张棋盘中有很多个不
- 一、概述之前写了篇Android OkHttp完全解析 是时候来了解OkHttp了,其实主要是作为okhttp的普及文章,当然里面也简单封装
- 一、:: 双冒号操作符在 Kotlin 中 , :: 双冒号操作符 的作用是 获取 类 , 对象 , 函数 , 属性 的 类型对象 引用 ;
- 站点IP访问频率限制 针对单个站点using System;using System.Collections.Generic;u
- 运行在TCP之上常见的网络应用协议有比如HTTP、FTP、SMTP、POP3、IMAP。TCP是TCP/IP体系中最重要的传输协议,它提供全
- 反射实例化类public class Person{ public string Name { get; set; }publi
- 本文实例为大家分享了Java判断对象是否为空的具体代码,供大家参考,具体内容如下package com.gj5u.publics.util;
- 本文实例讲述了C#(asp.net)多线程用法。分享给大家供大家参考,具体如下:using System;using System.Coll
- 在上一讲中,我们对Spring的基本使用进行了一个简单的回顾,接下来,我们就来看一下Spring核心功能结构。Spring核心功能结构Spr
- 数字可以标志货币、百分比、积分和电话号码等,就货币而言,在不同的国家会以不同的格式来定义,本实例将接收用户输入的数字,然后在控制台中输出其货
- RestTemplate加@Autowired注入不了1、在启动类加入如图箭头所示代码:然后在进行@Autowired发现不报错了。完美解决
- C#中添加窗口的步骤:1是添加窗口。2是在程序中使用new实例化窗口类对象,并显示窗口。1 添加窗口在解决方案管理器->主项目名称-&
- 本文实例讲述了Android编程使用GestureDetector实现简单手势监听与处理的方法。分享给大家供大家参考,具体如下:添加手势识别
- 问题背景: 我要在一个表单里同时一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该
- 本文实例为大家分享了Android判断当前App状态的具体实现代码,供大家参考,具体内容如下第一种: /** *判断当前应用程序
- java.math.BigDecimal及加减乘除计算BigDecimal简介BigDecimal用来对需要更大或更小的数进行任意精度的运算
- 介绍:Selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包
- 1.根据入参带分页参数进行sql查询分页 Criteria criteria = n