菜鸟教程之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股历史上最疯狂的一轮市值狂飙。 自春节后至今,ChatGPT概念股开始了暴走模式,短短半月时间,海天瑞声、开普云等ChatGPT概念股市值累计增加了近1400亿。 如此的爆炸效应,得益于ChatGPT所展现出商业化落地的巨大潜…...
linux使用systemctl
要使用 systemd 来控制 frps,需要先安装 systemd,然后在 /etc/systemd/system 目录下创建一个 frps.service 文件 安装systemd # yum yum install systemd # apt apt install systemd创建并编辑 frps.service 文件 [Unit] DescriptionFrp Server Serv…...
交换机和VLAN简介
一.二层设备(交换机和网桥)的区别简介 1.交换机: 2.网桥: 二.交换机原理介绍 三.VLAN概念介绍 1.VLAN将一个物理区域LAN划分为多个区域 2.作用: 3.标识方式VLAN ID 4.VLAN配置下MAC地址表的三元素 5.交换中的…...
想要拯救丢失的海康威视硬盘录像数据?可采用这三种恢复方法
海康威视作为全球领先的视频监控产品及解决方案提供商,其硬盘录像机可用于对大型公共场所、企事业单位及个人住宅等场所的安全监控。然而在实际使用中,有时会发生硬盘录像数据丢失的情况,这将对用户带来不小的损失和困扰。 硬盘录像数据丢失…...
每周一算法:高精度乘法(一)大整数乘整数
高精度乘法 乘法是我们在比赛中常用到运算之一,但在利用C++进行乘方或者阶乘计算时,由于其结果的增长速度很快,很容易就溢出了。例如: 13 ! = 6 , 227 , 020 , 800 13!=6,227,020,800 13!=6...
c++华为od面经
手撕代码: 力扣1004 最大连续1的个数 给定一个二进制数组 nums 和一个整数 k,如果可以翻转最多 k 个 0 ,则返回 数组中连续 1 的最大个数 。 输入:nums [1,1,1,0,0,0,1,1,1,1,0], K 2 输出:6 解释:[1,1,1…...
【郭东白架构课 模块二:创造价值】18|节点一:架构活动中为什么要做环境搭建?
你好,我是郭东白。在第 16、17 讲,我们讲解了架构师在架构活动中要起的作用,主要有达成共识、控制风险、保障交付和沉淀知识这四个方面。这是从架构师创造价值的维度来拆解的。 那么从这节课开始,我将从架构活动生命周期的维度上…...
15个awk的经典实战案例
目录 一、插入几个新字段 二、格式化个空白 三、筛选IPV4地址 命令及结果 第一种查询方式 第二种查询方式 第三种查询方式 四、读取.ini配置文件中的某段 命令及结果 第一种查询方式 第二种查询方式 五、根据某字段去重 命令及结果 第一种方式 第二种方式 六、…...
【JAVA】本地代码获取路径乱码
本地代码获取路径乱码 获取resources下资源乱码 解决方法: 获取路径后把返回值decode下就可以了. 用utf-8编码 String path this.getClass().getResource("").getPath();...
自然机器人最新发布:智能流程助手,与GPT深度融合
ChatGPT自2022年11月上线后就受到现象级地广泛关注,5天时间用户就已经突破百万,仅2个月时间月活用户就突破1亿,成为史上增速最快的消费级应用,远超TikTok、Facebook、Google等全球应用。它展现了类似人类的语言理解和对话交互能力…...
【Mybatis】4—动态SQL
⭐⭐⭐⭐⭐⭐ Github主页👉https://github.com/A-BigTree 笔记链接👉https://github.com/A-BigTree/Code_Learning ⭐⭐⭐⭐⭐⭐ 如果可以,麻烦各位看官顺手点个star~😊 如果文章对你有所帮助,可以点赞👍…...
事务传播特性和隔离级别
事务的四大特性 1.原子性(Atomicity):事务不可再分,要么都执行,要么都不执行。 2.一致性(Consistency):事务执行前后,数据的完整性保持一致,即修改前后数据总…...
socket网络编程
端口 :主机上一个应用程序的代号(端口不变) 为什么不用PID来表示一个应用 因为PID会变化,而端口是不变的 套接字进程间通信——跨越主机 1、主机字节序列和网络字节序列 主机字节序列分为大端字节序和小端字节序,不同…...
IO多路复用机制详解
高性能IO模型浅析 服务器端编程经常需要构造高性能的IO模型,常见的IO模型有四种: (1)同步阻塞IO(Blocking IO):即传统的IO模型。 (2)同步非阻塞IO(Non-blo…...
选择一款好用的营销项目管理可以更好帮您解决任何问题
营销项目管理软件哪个好用?使用Zoho Projects营销项目管理软件,您可以从营销活动中获得最佳结果,并获得可执行的见解。Zoho Projects的营销项目管理软件可让您和您的团队全面了解您的所有活动。监控您的社交渠道、跟踪结果并在一处进行交流。…...
计算机网络(第八版)第三章知识总结(期末复习可用)
本笔记来源于博主上课所记笔记整理,可能不全,欢迎大家批评指正,如果觉得有用记得点个赞,给博主点个关注...该笔记将会持续更新...整理不易,希望大家多多点赞。 第一章 第三章 数据链路层 数据链路层属于计算机网络的低…...
VScode配置8086汇编环境
目录 0、感慨 1、VScode的安装 2、下载MASM/TASM插件 3、测试汇编环境 新建文件 汇编文件配置 汇编代码的运行 0、感慨 搭配一个简单些的环境,对于我们汇编的学习很有帮助,在这里又不得不感叹vscode的强大,使用VScodeMASM/TASM插件就…...
银行数字化转型导师坚鹏:银行同业核心产品与营销策略解读
数字化背景下银行同业核心产品与营销策略解读课程背景: 数字化背景下,很多银行存在以下问题:不清楚银行同业核心产品发展现状?不清楚如何银行同业产品营销策略?不知道如何更好地挖掘他行优质客户? 课…...
在线答题考试小程序源码系统 支持在线刷题+考试二合一+安装部署教程
分享一个在线答题考试小程序源码系统,支持在线刷题考试二合一,程序包含前后端和详细的安装部署教程,可以用来给学生刷题,给员工刷题,给政企员工刷题,万能通用版适合任何行业在线刷题及考试。 系统功能一览&…...
基于FPGA的PID算法学习———实现PID比例控制算法
基于FPGA的PID算法学习 前言一、PID算法分析二、PID仿真分析1. PID代码2.PI代码3.P代码4.顶层5.测试文件6.仿真波形 总结 前言 学习内容:参考网站: PID算法控制 PID即:Proportional(比例)、Integral(积分&…...
React Native 开发环境搭建(全平台详解)
React Native 开发环境搭建(全平台详解) 在开始使用 React Native 开发移动应用之前,正确设置开发环境是至关重要的一步。本文将为你提供一份全面的指南,涵盖 macOS 和 Windows 平台的配置步骤,如何在 Android 和 iOS…...
边缘计算医疗风险自查APP开发方案
核心目标:在便携设备(智能手表/家用检测仪)部署轻量化疾病预测模型,实现低延迟、隐私安全的实时健康风险评估。 一、技术架构设计 #mermaid-svg-iuNaeeLK2YoFKfao {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg…...
云启出海,智联未来|阿里云网络「企业出海」系列客户沙龙上海站圆满落地
借阿里云中企出海大会的东风,以**「云启出海,智联未来|打造安全可靠的出海云网络引擎」为主题的阿里云企业出海客户沙龙云网络&安全专场于5.28日下午在上海顺利举办,现场吸引了来自携程、小红书、米哈游、哔哩哔哩、波克城市、…...
【大模型RAG】Docker 一键部署 Milvus 完整攻略
本文概要 Milvus 2.5 Stand-alone 版可通过 Docker 在几分钟内完成安装;只需暴露 19530(gRPC)与 9091(HTTP/WebUI)两个端口,即可让本地电脑通过 PyMilvus 或浏览器访问远程 Linux 服务器上的 Milvus。下面…...
蓝牙 BLE 扫描面试题大全(2):进阶面试题与实战演练
前文覆盖了 BLE 扫描的基础概念与经典问题蓝牙 BLE 扫描面试题大全(1):从基础到实战的深度解析-CSDN博客,但实际面试中,企业更关注候选人对复杂场景的应对能力(如多设备并发扫描、低功耗与高发现率的平衡)和前沿技术的…...
MMaDA: Multimodal Large Diffusion Language Models
CODE : https://github.com/Gen-Verse/MMaDA Abstract 我们介绍了一种新型的多模态扩散基础模型MMaDA,它被设计用于在文本推理、多模态理解和文本到图像生成等不同领域实现卓越的性能。该方法的特点是三个关键创新:(i) MMaDA采用统一的扩散架构…...
Unity | AmplifyShaderEditor插件基础(第七集:平面波动shader)
目录 一、👋🏻前言 二、😈sinx波动的基本原理 三、😈波动起来 1.sinx节点介绍 2.vertexPosition 3.集成Vector3 a.节点Append b.连起来 4.波动起来 a.波动的原理 b.时间节点 c.sinx的处理 四、🌊波动优化…...
如何在网页里填写 PDF 表格?
有时候,你可能希望用户能在你的网站上填写 PDF 表单。然而,这件事并不简单,因为 PDF 并不是一种原生的网页格式。虽然浏览器可以显示 PDF 文件,但原生并不支持编辑或填写它们。更糟的是,如果你想收集表单数据ÿ…...
九天毕昇深度学习平台 | 如何安装库?
pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple --user 举个例子: 报错 ModuleNotFoundError: No module named torch 那么我需要安装 torch pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple --user pip install 库名&#x…...
