当前位置: 首页 > 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;万能通用版适合任何行业在线刷题及考试。 系统功能一览&…...

终极免费方案:3步轻松解锁QQ音乐加密文件,让音乐随处可听

终极免费方案&#xff1a;3步轻松解锁QQ音乐加密文件&#xff0c;让音乐随处可听 【免费下载链接】qmcflac2mp3 直接将qmcflac文件转换成mp3文件&#xff0c;突破QQ音乐的格式限制 项目地址: https://gitcode.com/gh_mirrors/qm/qmcflac2mp3 你是否曾遇到过这样的情况&a…...

Linuxbonding链路生产排障流程

Linuxbonding链路生产排障流程这是一篇面向中级 Linux 使用者的技术文章&#xff0c;主题聚焦在bonding链路&#xff0c;重点讨论链路聚合、冗余切换和接口状态。在真实生产环境中&#xff0c;bonding链路相关问题往往不会以单一错误形式出现&#xff0c;而是混杂在日志、权限、…...

NS-USBLoader:Switch游戏管理终极指南 - 如何实现一键安装与系统引导?

NS-USBLoader&#xff1a;Switch游戏管理终极指南 - 如何实现一键安装与系统引导&#xff1f; 【免费下载链接】ns-usbloader Awoo Installer and GoldLeaf uploader of the NSPs (and other files), RCM payload injector, application for split/merge files. 项目地址: ht…...

OpenSpeedy终极指南:如何通过开源游戏加速工具突破帧率限制

OpenSpeedy终极指南&#xff1a;如何通过开源游戏加速工具突破帧率限制 【免费下载链接】OpenSpeedy &#x1f3ae; An open-source game speed modifier. 项目地址: https://gitcode.com/gh_mirrors/op/OpenSpeedy 你是否厌倦了游戏中的卡顿和帧率限制&#xff1f;Open…...

Arm CoreLink PCK-600电源管理架构与寄存器编程详解

1. Arm CoreLink PCK-600电源控制架构解析在嵌入式系统设计中&#xff0c;电源管理单元&#xff08;PMU&#xff09;是实现高效能耗控制的核心组件。Arm CoreLink PCK-600作为业界领先的电源控制解决方案&#xff0c;其架构设计体现了现代SoC电源管理的先进理念。PCK-600系列采…...

乌尔都语语音合成落地难?揭秘ElevenLabs未公开的ur-PK语言代码陷阱与ISO 639-3双标适配规范(仅限首批127家认证开发者知晓)

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;乌尔都语语音合成落地难&#xff1f;揭秘ElevenLabs未公开的ur-PK语言代码陷阱与ISO 639-3双标适配规范&#xff08;仅限首批127家认证开发者知晓&#xff09; ElevenLabs 官方文档中仅标注 ur 为乌尔…...

树莓派机械爪项目实战:从硬件连接到Python控制全解析

1. 项目概述&#xff1a;当树莓派遇上机械爪最近在折腾一个挺有意思的小项目&#xff0c;叫Demwunz/openclaw-pi-installation。光看这个名字&#xff0c;就能猜到个大概&#xff1a;这是一个为树莓派&#xff08;Raspberry Pi&#xff09;准备的机械爪&#xff08;Claw&#x…...

mg3640s,ts8080,ts8100,g5080,g3800,g4800,ix6780,ts8180报错5B00,P07,E08,5b02,1704,1700,5b04佳能V6.200,亲测有用

下载&#xff1a;点这里下载 备用下载&#xff1a;https://pan.baidu.com/s/1WrPFvdV8sq-qI3_NgO2EvA?pwd0000 常见型号如下&#xff1a; G系列 G1000、G1100、G1200、G1400、G1500、G1800、G1900、G1010、G1110、G1120、G1410、G1420、G1411、G1510、G1520、G1810、G1820、…...

ElevenLabs克隆成功率从31%飙升至96.7%:基于LPC共振峰校准+Prosody Transfer双引擎微调法(实测数据包已脱敏上传)

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;ElevenLabs语音克隆方法概览 ElevenLabs 提供了高保真、低延迟的语音克隆能力&#xff0c;其核心依赖于少量高质量语音样本&#xff08;通常 1–3 分钟&#xff09;与上下文感知的零样本/少样本微调技术…...

MCP服务器生产级部署:从Docker到Kubernetes的完整工程化实践

1. 项目概述&#xff1a;一个为MCP服务器量身定制的部署蓝图如果你正在开发或使用一个基于模型上下文协议&#xff08;Model Context Protocol&#xff0c; MCP&#xff09;的服务器&#xff0c;并且为如何将其优雅、可靠地部署到生产环境而头疼&#xff0c;那么你很可能需要的…...