我想要一个在Linux终端中运行的Android服务(用Kotlin编写(在它运行的终端中打印出一条消息。主要的Kotlin类在这个文件中(我克隆了那个repo(。
我想用各种方式修改它,但现在我只想看看是否可以打印到终端。所以我尝试添加像这样的语句
print("message")
println("message")
Log.d(TAG, "message")
Log.i(TAG, "message")
等等。(另见另一个SO问题,它提出了这些问题,似乎是出于某种不同的目的(。
我的问题:
虽然"message"
确实出现在Android
日志中(与adb logcat
一起查看(,并且消息类型与我要求的日志类型匹配(例如,对于Log.i
,它在日志中显示为I <service-name>: message
(,但我希望直接在我运行了启动服务的adb
命令的终端中看到它。
这可能吗?
我从未发现如何通过adb
调用Android服务来实现这一点,所以我改用广播接收器。
我的清单文件现在注册接收器:
<?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>"
参考
该解决方案改编自这个旧的应用程序,该应用程序类似地使用广播接收器来获取/设置剪贴板。