gpt4 book ai didi

android - 将文本检索到 Linux 终端以使用 adb 运行 Android 服务

转载 作者:行者123 更新时间:2023-12-02 13:41:11 25 4
gpt4 key购买 nike

我想要一个在 Linux 终端中运行的 Android 服务(用 Kotlin 编写)在运行它的终端中打印出一条消息。主要的 Kotlin 类在 this file 中(我克隆了那个仓库)。
我想以各种方式修改它,但现在我只想看看是否可以打印到终端。所以我尝试添加类似的语句

print("message")
println("message")
Log.d(TAG, "message")
Log.i(TAG, "message")
等等(另见 this other SO question,它提出了这些,似乎是出于不同的目的)。
我的问题:
"message"确实出现在 Android日志(使用 adb logcat 查看),并且消息类型与我要求的日志记录类型匹配(例如,对于 Log.i 它在日志中显示为 I <service-name>: message ),但我希望直接在终端中查看它我已经运行了 adb启动服务的命令。
这可能吗?

最佳答案

我从来没有通过调用 Android service 找到如何做到这一点。通过 adb ,所以我求助于 broadcast receiver反而。
我的 manifest file现在注册接收器:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grobber.cliprecv">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".InfoScreenActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver" android:exported="true" android:enabled="true">
<intent-filter>
<action android:name="get" />
<action android:name="set" />
</intent-filter>
</receiver>
</application>
</manifest>
(请注意,该应用程序现在根本没有服务)。反过来,接收器类在 Kotlin 中定义。文件如下:
private const val TAG = "MyBroadcastReceiver"

class MyBroadcastReceiver :
BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
if (intent.getAction().equals("get")) {
val res: String
if (clipboard.hasPrimaryClip()) {
val cliptext = clipboard.getPrimaryClip()?.getItemAt(0)?.coerceToText(context)?: ""
res=cliptext.toString()
} else {
res = ""
}
setResultData(res)
} else if (intent.getAction().equals("set")) {
val str: String? = intent.getStringExtra("text")
clipboard.primaryClip = ClipData.newPlainText(TAG, str)
}
}
}
现在,将 Android 设备连接到计算机并在前台运行应用程序,运行
 adb shell am broadcast -n com.grobber.cliprecv/.MyBroadcastReceiver -a get
会将终端中剪贴板的内容返回为 data输出部分:
$ adb shell am broadcast -n com.grobber.cliprecv/.MyBroadcastReceiver -a get
---
Broadcasting: Intent { act=get flg=0x400000 cmp=com.grobber.cliprecv/.MyBroadcastReceiver }
Broadcast completed: result=0, data="<CLIPBOARD CONTENTS>"

引用
该解决方案改编自 this older app同样使用广播接收器来获取/设置剪贴板。

关于android - 将文本检索到 Linux 终端以使用 adb 运行 Android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63339408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com