news 2026/10/20 5:11:19

Android 控件 - 悬浮常驻文本交互(IBinder 实现、BroadcastReceiver 实现)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Android 控件 - 悬浮常驻文本交互(IBinder 实现、BroadcastReceiver 实现)

IBinder 实现

1、Service
  • FloatTextService.java
publicclassFloatTextServiceextendsService{privateTextViewtvFloat;privateWindowManagerwindowManager;privatefinalIBinderbinder=newFloatTextServiceBinder();publicclassFloatTextServiceBinderextendsBinder{publicFloatTextServicegetService(){returnFloatTextService.this;}}@Nullable@OverridepublicIBinderonBind(Intentintent){returnbinder;}@OverridepublicvoidonCreate(){super.onCreate();windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);// 创建布局参数WindowManager.LayoutParamsparams=newWindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT,Build.VERSION.SDK_INT>=Build.VERSION_CODES.O?WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY:WindowManager.LayoutParams.TYPE_PHONE,WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,PixelFormat.TRANSLUCENT);// 设置位置为左下角params.gravity=Gravity.BOTTOM|Gravity.START;params.x=0;params.y=0;LayoutInflaterinflater=LayoutInflater.from(this);tvFloat=(TextView)inflater.inflate(R.layout.float_text,null);// 添加到窗口windowManager.addView(tvFloat,params);}publicvoidshowFloatText(Stringtext){tvFloat.setText(text);}@OverridepublicvoidonDestroy(){super.onDestroy();if(tvFloat!=null){windowManager.removeView(tvFloat);}}}
  • float_text.xml
<?xml version="1.0" encoding="utf-8"?><TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/tv_float"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="12dp"android:textSize="14sp"/>
2、Manifest
  • AndroidManifest.xml
<uses-permissionandroid:name="android.permission.SYSTEM_ALERT_WINDOW"/><application>...<serviceandroid:name=".viewfixed.service.FloatTextService"android:enabled="true"android:exported="false"/></application>
3、Activity Layout
  • activity_float_text_service_test.xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".viewfixed.FloatTextServiceTestActivity"><Buttonandroid:id="@+id/btn_show_float_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="显示悬浮文本"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"/></androidx.constraintlayout.widget.ConstraintLayout>
4、Activity Code
  • FloatTextServiceTestActivity.java
publicclassFloatTextServiceTestActivityextendsAppCompatActivity{privateActivityResultLauncher<Intent>floatPermissionLauncher;privateFloatTextServicefloatTextService;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_float_text_service_test);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});test();}privatevoidtest(){floatPermissionLauncher=registerForActivityResult(newActivityResultContracts.StartActivityForResult(),result->{if(checkFloatPermission()){createFloatText();}else{Toast.makeText(this,"未开启浮窗权限",Toast.LENGTH_SHORT).show();}});if(checkFloatPermission()){createFloatText();}else{requestFloatPermission();}ButtonbtnShowFloatText=findViewById(R.id.btn_show_float_text);btnShowFloatText.setOnClickListener(v->{floatTextService.showFloatText("Hello Float Text");});}privatebooleancheckFloatPermission(){if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){returnSettings.canDrawOverlays(this);}returntrue;}privatevoidrequestFloatPermission(){Intentintent=newIntent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:"+getPackageName()));floatPermissionLauncher.launch(intent);}privatevoidcreateFloatText(){bindService(newIntent(this,FloatTextService.class),newServiceConnection(){@OverridepublicvoidonServiceConnected(ComponentNamecomponentName,IBinderiBinder){FloatTextService.FloatTextServiceBinderbinder=(FloatTextService.FloatTextServiceBinder)iBinder;floatTextService=binder.getService();}@OverridepublicvoidonServiceDisconnected(ComponentNamecomponentName){}},BIND_AUTO_CREATE);}}

BroadcastReceiver 实现

1、Service
  • FloatTextService.java
publicclassFloatTextServiceextendsService{privateTextViewtvFloat;privateWindowManagerwindowManager;privatefinalIBinderbinder=newFloatTextServiceBinder();publicclassFloatTextServiceBinderextendsBinder{publicFloatTextServicegetService(){returnFloatTextService.this;}}publicstaticfinalStringACTION="SHOW_FLOAT_TEXT";privateBroadcastReceiverFloatTextServiceBroadcastReceiver;@Nullable@OverridepublicIBinderonBind(Intentintent){returnbinder;}@OverridepublicvoidonCreate(){super.onCreate();windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);// 创建布局参数WindowManager.LayoutParamsparams=newWindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT,Build.VERSION.SDK_INT>=Build.VERSION_CODES.O?WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY:WindowManager.LayoutParams.TYPE_PHONE,WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,PixelFormat.TRANSLUCENT);// 设置位置为左下角params.gravity=Gravity.BOTTOM|Gravity.START;params.x=0;params.y=0;LayoutInflaterinflater=LayoutInflater.from(this);tvFloat=(TextView)inflater.inflate(R.layout.float_text,null);// 添加到窗口windowManager.addView(tvFloat,params);FloatTextServiceBroadcastReceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){if(intent.hasExtra("text")){StringnewText=intent.getStringExtra("text");tvFloat.setText(newText);}}};IntentFilterintentFilter=newIntentFilter();intentFilter.addAction(ACTION);registerReceiver(FloatTextServiceBroadcastReceiver,intentFilter);}publicvoidshowFloatText(Stringtext){tvFloat.setText(text);}@OverridepublicvoidonDestroy(){super.onDestroy();if(tvFloat!=null){windowManager.removeView(tvFloat);}}}
  • float_text.xml
<?xml version="1.0" encoding="utf-8"?><TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/tv_float"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="12dp"android:textSize="14sp"/>
2、Manifest
  • AndroidManifest.xml
<uses-permissionandroid:name="android.permission.SYSTEM_ALERT_WINDOW"/><application>...<serviceandroid:name=".viewfixed.service.FloatTextService"android:enabled="true"android:exported="false"/></application>
3、Activity Layout
  • activity_float_text_service_test.xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".viewfixed.FloatTextServiceTestActivity"><Buttonandroid:id="@+id/btn_show_float_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="显示悬浮文本"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"/></androidx.constraintlayout.widget.ConstraintLayout>
4、Activity Code
  • FloatTextServiceTestActivity.java
publicclassFloatTextServiceTestActivityextendsAppCompatActivity{privateActivityResultLauncher<Intent>floatPermissionLauncher;privateFloatTextServicefloatTextService;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_float_text_service_test);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});test();}privatebooleancheckFloatPermission(){if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){returnSettings.canDrawOverlays(this);}returntrue;}privatevoidrequestFloatPermission(){Intentintent=newIntent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:"+getPackageName()));floatPermissionLauncher.launch(intent);}privatevoidcreateFloatText(){bindService(newIntent(this,FloatTextService.class),newServiceConnection(){@OverridepublicvoidonServiceConnected(ComponentNamecomponentName,IBinderiBinder){FloatTextService.FloatTextServiceBinderbinder=(FloatTextService.FloatTextServiceBinder)iBinder;floatTextService=binder.getService();}@OverridepublicvoidonServiceDisconnected(ComponentNamecomponentName){}},BIND_AUTO_CREATE);}privatevoidtest(){floatPermissionLauncher=registerForActivityResult(newActivityResultContracts.StartActivityForResult(),result->{if(checkFloatPermission()){createFloatText();}else{Toast.makeText(this,"未开启浮窗权限",Toast.LENGTH_SHORT).show();}});if(checkFloatPermission()){createFloatText();}else{requestFloatPermission();}ButtonbtnShowFloatText=findViewById(R.id.btn_show_float_text);btnShowFloatText.setOnClickListener(v->{Intentintent=newIntent(FloatTextService.ACTION);intent.putExtra("text","Hello Float Text");sendBroadcast(intent);});}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/10/5 6:17:26

LunaTranslator:打破语言障碍,畅享日文游戏乐趣

LunaTranslator&#xff1a;打破语言障碍&#xff0c;畅享日文游戏乐趣 【免费下载链接】LunaTranslator Galgame翻译器&#xff0c;支持HOOK、OCR、剪贴板等。Visual Novel Translator , support HOOK / OCR / clipboard 项目地址: https://gitcode.com/GitHub_Trending/lu/…

作者头像 李华
网站建设 2026/10/16 23:47:42

memtest_vulkan:显卡内存稳定性的终极检测神器

memtest_vulkan&#xff1a;显卡内存稳定性的终极检测神器 【免费下载链接】memtest_vulkan Vulkan compute tool for testing video memory stability 项目地址: https://gitcode.com/gh_mirrors/me/memtest_vulkan 还在为游戏卡顿、系统崩溃而烦恼吗&#xff1f;这些问…

作者头像 李华
网站建设 2026/10/17 21:23:00

显卡内存终极检测指南:6分钟快速验证GPU稳定性

显卡内存终极检测指南&#xff1a;6分钟快速验证GPU稳定性 【免费下载链接】memtest_vulkan Vulkan compute tool for testing video memory stability 项目地址: https://gitcode.com/gh_mirrors/me/memtest_vulkan 你是否在玩游戏时突然遭遇花屏、系统无故重启&#x…

作者头像 李华
网站建设 2026/10/19 21:00:34

Anki智能记忆革命:打造个人专属的高效学习系统

Anki智能记忆革命&#xff1a;打造个人专属的高效学习系统 【免费下载链接】anki Ankis shared backend and web components, and the Qt frontend 项目地址: https://gitcode.com/GitHub_Trending/an/anki 在信息爆炸的时代&#xff0c;我们每天都在接收海量知识&#…

作者头像 李华
网站建设 2026/10/13 15:32:29

Dify插件开发必备文档清单(仅限内部流传的完整版)

第一章&#xff1a;Dify插件开发概述Dify 是一个支持可扩展架构的低代码 AI 应用开发平台&#xff0c;其插件系统允许开发者通过自定义模块扩展平台能力。插件可用于接入外部 API、封装业务逻辑或增强数据处理流程。通过插件机制&#xff0c;用户可以在不修改核心代码的前提下&…

作者头像 李华
网站建设 2026/10/19 20:08:24

终极Emby美化2025:个性化定制媒体中心完整指南

还在为Emby媒体服务器单调的界面设计而烦恼吗&#xff1f;想要让影音库焕然一新却不知从何入手&#xff1f;Emby Crx美化插件作为专为Chrome内核浏览器和EmbyServer设计的开源工具&#xff0c;通过自定义CSS样式和JavaScript功能&#xff0c;为你的媒体中心注入全新活力。无需专…

作者头像 李华