当前位置: 首页 > news >正文

菜鸟教程之Android学习笔记Service

Service初步

一、StartService启动Service的调用顺序

MainActivity.java

package com.example.test2;import androidx.appcompat.app.AppCompatActivity;import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;public class MainActivity extends Activity {private Button start;private Button stop;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);start = (Button) findViewById(R.id.btnstart);stop = (Button) findViewById(R.id.btnstop);//创建启动Service的Intent,以及Intent属性Intent intent = new Intent();intent.setAction("com.example.test2.TEST_SERVICE1");intent.setPackage(getPackageName());//Intent intent = new Intent(this,TestService1.class);//为两个按钮设置点击事件,分别是启动与停止servicestart.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {startService(intent);}});stop.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {stopService(intent);}});}
}

TestService1.java

package com.example.test2;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;import java.security.Provider;public class TestService1 extends Service {private final String TAG = "TestService1";public IBinder onBind(Intent intent) {System.out.println("onBind方法被调用!");Log.i(TAG, "onBind方法被调用!");return null;}public void onCreate() {System.out.println("onCreate方法被调用!");Log.i(TAG, "onCreate方法被调用!");super.onCreate();}public int onStartCommand(Intent intent, int flags, int startId) {System.out.println("onStartCommand方法被调用!");Log.i(TAG, "onStartCommand方法被调用!");return super.onStartCommand(intent, flags, startId);}public void onDestroy() {System.out.println("onDestory方法被调用!");Log.i(TAG, "onDestory方法被调用!");super.onDestroy();}
}

AndroidManifest.xml

        <service android:name=".TestService1"android:exported="true"><intent-filter><action android:name="com.example.test2.TEST_SERVICE1"/></intent-filter></service>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="200dp"android:id="@+id/btnstart"android:layout_gravity="center_horizontal"android:text="开始服务" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btnstop"android:layout_marginTop="100dp"android:layout_gravity="center_horizontal"android:text="停止服务" /></LinearLayout>

二. BindService启动Service的顺序

MainActivity.java

package com.example.test2;import androidx.appcompat.app.AppCompatActivity;import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class MainActivity extends Activity {private Button btnbind;private Button btncancel;private Button btnstatus;//保持所启动的Service的IBinder对象,同时定义一个ServiceConnection对象TestService2.MyBinder binder;private ServiceConnection conn = new ServiceConnection() {//Activity与Service断开连接时回调该方法@Overridepublic void onServiceDisconnected(ComponentName name) {System.out.println("------Service DisConnected-------");}//Activity与Service连接成功时回调该方法@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {System.out.println("------Service Connected-------");binder = (TestService2.MyBinder) service;}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnbind = (Button) findViewById(R.id.btnbind);btncancel = (Button) findViewById(R.id.btncancel);btnstatus  = (Button) findViewById(R.id.btnstatus);Intent intent = new Intent();intent.setAction("com.example.test2.TEST_SERVICE2");intent.setPackage(getPackageName());btnbind.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//绑定servicebindService(intent, conn, Service.BIND_AUTO_CREATE);}});btncancel.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//解除service绑定unbindService(conn);}});btnstatus.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getApplicationContext(), "Service的count的值为:"+ binder.getCount(), Toast.LENGTH_SHORT).show();}});}
}

TestService2.java

package com.example.test2;import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;public class TestService2 extends Service {private final String TAG = "TestService2";private int count;private boolean quit;//定义onBinder方法所返回的对象private MyBinder binder = new MyBinder();public class MyBinder extends Binder {public int getCount() {return count;}}//必须实现的方法,绑定改Service时回调该方法@Overridepublic IBinder onBind(Intent intent) {Log.i(TAG, "onBind方法被调用!");return binder;}//Service被创建时回调@Overridepublic void onCreate() {super.onCreate();Log.i(TAG, "onCreate方法被调用!");//创建一个线程动态地修改count的值new Thread() {public void run() {while(!quit) {try {Thread.sleep(1000);} catch (InterruptedException e){e.printStackTrace();}count++;}};}.start();}//Service断开连接时回调@Overridepublic boolean onUnbind(Intent intent) {Log.i(TAG, "onUnbind方法被调用!");return true;}//Service被关闭前回调@Overridepublic void onDestroy() {super.onDestroy();this.quit = true;Log.i(TAG, "onDestroyed方法被调用!");}@Overridepublic void onRebind(Intent intent) {Log.i(TAG, "onRebind方法被调用!");super.onRebind(intent);}
}

AndroidManifest.xml

        <service android:name=".TestService2"android:exported="true"><intent-filter><action android:name="com.example.test2.TEST_SERVICE2"/></intent-filter></service>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="150dp"android:id="@+id/btnbind"android:layout_gravity="center_horizontal"android:text="锁定Service" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btncancel"android:layout_marginTop="50dp"android:layout_gravity="center_horizontal"android:text="解除锁定" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btnstatus"android:layout_marginTop="50dp"android:layout_gravity="center_horizontal"android:text="获取Service状态" /></LinearLayout>

Service进阶

MainActivity.java

package com.example.test2;import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent it1 = new Intent("com.example.test2.TEST_SERVICE3");it1.setPackage(getPackageName());Bundle b1 = new Bundle();b1.putString("param", "s1");it1.putExtras(b1);Intent it2 = new Intent("com.example.test2.TEST_SERVICE3");it2.setPackage(getPackageName());Bundle b2 = new Bundle();b2.putString("param", "s2");it2.putExtras(b2);Intent it3 = new Intent("com.example.test2.TEST_SERVICE3");it3.setPackage(getPackageName());Bundle b3 = new Bundle();b3.putString("param", "s3");it3.putExtras(b3);//接着启动多次IntentService,每次启动,都会新建一个工作线程//但始终只有一个IntentService实例startService(it1);startService(it2);startService(it3);}
}

TestService3.java

package com.example.test2;import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;public class TestService3 extends IntentService {private final String TAG = "TestService3";//必须实现父类的构造方法public TestService3() {super("TestService3");}//必须重写的核心方法@Overrideprotected void onHandleIntent(Intent intent) {//Intent是从Activity发过来的,携带识别参数,根据参数不同执行不同的任务String action = intent.getExtras().getString("param");if(action.equals("s1"))Log.i(TAG,"启动service1");else if(action.equals("s2"))Log.i(TAG,"启动service2");else if(action.equals("s3"))Log.i(TAG,"启动service3");//让服务休眠2秒try{Thread.sleep(1000);}catch(InterruptedException e){e.printStackTrace();}}//重写其他方法,用于查看方法的调用顺序@Overridepublic IBinder onBind(Intent intent) {Log.i(TAG,"onBind");return super.onBind(intent);}@Overridepublic void onCreate() {Log.i(TAG,"onCreate");super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i(TAG,"onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void setIntentRedelivery(boolean enabled) {super.setIntentRedelivery(enabled);Log.i(TAG,"setIntentRedelivery");}@Overridepublic void onDestroy() {Log.i(TAG,"onDestroy");super.onDestroy();}
}

https://www.runoob.com/w3cnote/android-tutorial-service-1.html

相关文章:

菜鸟教程之Android学习笔记Service

Service初步 一、StartService启动Service的调用顺序 MainActivity.java package com.example.test2;import androidx.appcompat.app.AppCompatActivity;import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View;…...

半个月狂飙1000亿,ChatGPT概念股凭什么?

ChatGPT 掀起了AI股历史上最疯狂的一轮市值狂飙。 自春节后至今&#xff0c;ChatGPT概念股开始了暴走模式&#xff0c;短短半月时间&#xff0c;海天瑞声、开普云等ChatGPT概念股市值累计增加了近1400亿。 如此的爆炸效应&#xff0c;得益于ChatGPT所展现出商业化落地的巨大潜…...

linux使用systemctl

要使用 systemd 来控制 frps&#xff0c;需要先安装 systemd&#xff0c;然后在 /etc/systemd/system 目录下创建一个 frps.service 文件 安装systemd # yum yum install systemd # apt apt install systemd创建并编辑 frps.service 文件 [Unit] DescriptionFrp Server Serv…...

交换机和VLAN简介

一.二层设备&#xff08;交换机和网桥&#xff09;的区别简介 1.交换机&#xff1a; 2.网桥&#xff1a; 二.交换机原理介绍 三.VLAN概念介绍 1.VLAN将一个物理区域LAN划分为多个区域 2.作用&#xff1a; 3.标识方式VLAN ID 4.VLAN配置下MAC地址表的三元素 5.交换中的…...

想要拯救丢失的海康威视硬盘录像数据?可采用这三种恢复方法

海康威视作为全球领先的视频监控产品及解决方案提供商&#xff0c;其硬盘录像机可用于对大型公共场所、企事业单位及个人住宅等场所的安全监控。然而在实际使用中&#xff0c;有时会发生硬盘录像数据丢失的情况&#xff0c;这将对用户带来不小的损失和困扰。 硬盘录像数据丢失…...

每周一算法:高精度乘法(一)大整数乘整数

高精度乘法 乘法是我们在比赛中常用到运算之一,但在利用C++进行乘方或者阶乘计算时,由于其结果的增长速度很快,很容易就溢出了。例如: 13 ! = 6 , 227 , 020 , 800 13!=6,227,020,800 13!=6...

c++华为od面经

手撕代码&#xff1a; 力扣1004 最大连续1的个数 给定一个二进制数组 nums 和一个整数 k&#xff0c;如果可以翻转最多 k 个 0 &#xff0c;则返回 数组中连续 1 的最大个数 。 输入&#xff1a;nums [1,1,1,0,0,0,1,1,1,1,0], K 2 输出&#xff1a;6 解释&#xff1a;[1,1,1…...

【郭东白架构课 模块二:创造价值】18|节点一:架构活动中为什么要做环境搭建?

你好&#xff0c;我是郭东白。在第 16、17 讲&#xff0c;我们讲解了架构师在架构活动中要起的作用&#xff0c;主要有达成共识、控制风险、保障交付和沉淀知识这四个方面。这是从架构师创造价值的维度来拆解的。 那么从这节课开始&#xff0c;我将从架构活动生命周期的维度上…...

15个awk的经典实战案例

目录 一、插入几个新字段 二、格式化个空白 三、筛选IPV4地址 命令及结果 第一种查询方式 第二种查询方式 第三种查询方式 四、读取.ini配置文件中的某段 命令及结果 第一种查询方式 第二种查询方式 五、根据某字段去重 命令及结果 第一种方式 第二种方式 六、…...

【JAVA】本地代码获取路径乱码

本地代码获取路径乱码 获取resources下资源乱码 解决方法&#xff1a; 获取路径后把返回值decode下就可以了. 用utf-8编码 String path this.getClass().getResource("").getPath();...

自然机器人最新发布:智能流程助手,与GPT深度融合

ChatGPT自2022年11月上线后就受到现象级地广泛关注&#xff0c;5天时间用户就已经突破百万&#xff0c;仅2个月时间月活用户就突破1亿&#xff0c;成为史上增速最快的消费级应用&#xff0c;远超TikTok、Facebook、Google等全球应用。它展现了类似人类的语言理解和对话交互能力…...

【Mybatis】4—动态SQL

⭐⭐⭐⭐⭐⭐ Github主页&#x1f449;https://github.com/A-BigTree 笔记链接&#x1f449;https://github.com/A-BigTree/Code_Learning ⭐⭐⭐⭐⭐⭐ 如果可以&#xff0c;麻烦各位看官顺手点个star~&#x1f60a; 如果文章对你有所帮助&#xff0c;可以点赞&#x1f44d;…...

事务传播特性和隔离级别

事务的四大特性 1.原子性&#xff08;Atomicity&#xff09;&#xff1a;事务不可再分&#xff0c;要么都执行&#xff0c;要么都不执行。 2.一致性&#xff08;Consistency&#xff09;&#xff1a;事务执行前后&#xff0c;数据的完整性保持一致&#xff0c;即修改前后数据总…...

socket网络编程

端口 &#xff1a;主机上一个应用程序的代号&#xff08;端口不变&#xff09; 为什么不用PID来表示一个应用 因为PID会变化&#xff0c;而端口是不变的 套接字进程间通信——跨越主机 1、主机字节序列和网络字节序列 主机字节序列分为大端字节序和小端字节序&#xff0c;不同…...

IO多路复用机制详解

高性能IO模型浅析 服务器端编程经常需要构造高性能的IO模型&#xff0c;常见的IO模型有四种&#xff1a; &#xff08;1&#xff09;同步阻塞IO&#xff08;Blocking IO&#xff09;&#xff1a;即传统的IO模型。 &#xff08;2&#xff09;同步非阻塞IO&#xff08;Non-blo…...

选择一款好用的营销项目管理可以更好帮您解决任何问题

营销项目管理软件哪个好用&#xff1f;使用Zoho Projects营销项目管理软件&#xff0c;您可以从营销活动中获得最佳结果&#xff0c;并获得可执行的见解。Zoho Projects的营销项目管理软件可让您和您的团队全面了解您的所有活动。监控您的社交渠道、跟踪结果并在一处进行交流。…...

计算机网络(第八版)第三章知识总结(期末复习可用)

本笔记来源于博主上课所记笔记整理&#xff0c;可能不全&#xff0c;欢迎大家批评指正&#xff0c;如果觉得有用记得点个赞&#xff0c;给博主点个关注...该笔记将会持续更新...整理不易&#xff0c;希望大家多多点赞。 第一章 第三章 数据链路层 数据链路层属于计算机网络的低…...

VScode配置8086汇编环境

目录 0、感慨 1、VScode的安装 2、下载MASM/TASM插件 3、测试汇编环境 新建文件 汇编文件配置 汇编代码的运行 0、感慨 搭配一个简单些的环境&#xff0c;对于我们汇编的学习很有帮助&#xff0c;在这里又不得不感叹vscode的强大&#xff0c;使用VScodeMASM/TASM插件就…...

银行数字化转型导师坚鹏:银行同业核心产品与营销策略解读

数字化背景下银行同业核心产品与营销策略解读课程背景&#xff1a; 数字化背景下&#xff0c;很多银行存在以下问题&#xff1a;不清楚银行同业核心产品发展现状&#xff1f;不清楚如何银行同业产品营销策略&#xff1f;不知道如何更好地挖掘他行优质客户&#xff1f; 课…...

在线答题考试小程序源码系统 支持在线刷题+考试二合一+安装部署教程

分享一个在线答题考试小程序源码系统&#xff0c;支持在线刷题考试二合一&#xff0c;程序包含前后端和详细的安装部署教程&#xff0c;可以用来给学生刷题&#xff0c;给员工刷题&#xff0c;给政企员工刷题&#xff0c;万能通用版适合任何行业在线刷题及考试。 系统功能一览&…...

后进先出(LIFO)详解

LIFO 是 Last In, First Out 的缩写&#xff0c;中文译为后进先出。这是一种数据结构的工作原则&#xff0c;类似于一摞盘子或一叠书本&#xff1a; 最后放进去的元素最先出来 -想象往筒状容器里放盘子&#xff1a; &#xff08;1&#xff09;你放进的最后一个盘子&#xff08…...

DAY 47

三、通道注意力 3.1 通道注意力的定义 # 新增&#xff1a;通道注意力模块&#xff08;SE模块&#xff09; class ChannelAttention(nn.Module):"""通道注意力模块(Squeeze-and-Excitation)"""def __init__(self, in_channels, reduction_rat…...

JDK 17 新特性

#JDK 17 新特性 /**************** 文本块 *****************/ python/scala中早就支持&#xff0c;不稀奇 String json “”" { “name”: “Java”, “version”: 17 } “”"; /**************** Switch 语句 -> 表达式 *****************/ 挺好的&#xff…...

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据 Power Query 具有大量专门帮助您清理和准备数据以供分析的功能。 您将了解如何简化复杂模型、更改数据类型、重命名对象和透视数据。 您还将了解如何分析列&#xff0c;以便知晓哪些列包含有价值的数据&#xff0c;…...

STM32HAL库USART源代码解析及应用

STM32HAL库USART源代码解析 前言STM32CubeIDE配置串口USART和UART的选择使用模式参数设置GPIO配置DMA配置中断配置硬件流控制使能生成代码解析和使用方法串口初始化__UART_HandleTypeDef结构体浅析HAL库代码实际使用方法使用轮询方式发送使用轮询方式接收使用中断方式发送使用中…...

Web中间件--tomcat学习

Web中间件–tomcat Java虚拟机详解 什么是JAVA虚拟机 Java虚拟机是一个抽象的计算机&#xff0c;它可以执行Java字节码。Java虚拟机是Java平台的一部分&#xff0c;Java平台由Java语言、Java API和Java虚拟机组成。Java虚拟机的主要作用是将Java字节码转换为机器代码&#x…...

[ACTF2020 新生赛]Include 1(php://filter伪协议)

题目 做法 启动靶机&#xff0c;点进去 点进去 查看URL&#xff0c;有 ?fileflag.php说明存在文件包含&#xff0c;原理是php://filter 协议 当它与包含函数结合时&#xff0c;php://filter流会被当作php文件执行。 用php://filter加编码&#xff0c;能让PHP把文件内容…...

uniapp 小程序 学习(一)

利用Hbuilder 创建项目 运行到内置浏览器看效果 下载微信小程序 安装到Hbuilder 下载地址 &#xff1a;开发者工具默认安装 设置服务端口号 在Hbuilder中设置微信小程序 配置 找到运行设置&#xff0c;将微信开发者工具放入到Hbuilder中&#xff0c; 打开后出现 如下 bug 解…...

Kafka主题运维全指南:从基础配置到故障处理

#作者&#xff1a;张桐瑞 文章目录 主题日常管理1. 修改主题分区。2. 修改主题级别参数。3. 变更副本数。4. 修改主题限速。5.主题分区迁移。6. 常见主题错误处理常见错误1&#xff1a;主题删除失败。常见错误2&#xff1a;__consumer_offsets占用太多的磁盘。 主题日常管理 …...

学习一下用鸿蒙​​DevEco Studio HarmonyOS5实现百度地图

在鸿蒙&#xff08;HarmonyOS5&#xff09;中集成百度地图&#xff0c;可以通过以下步骤和技术方案实现。结合鸿蒙的分布式能力和百度地图的API&#xff0c;可以构建跨设备的定位、导航和地图展示功能。 ​​1. 鸿蒙环境准备​​ ​​开发工具​​&#xff1a;下载安装 ​​De…...