fix(android): 修复投屏崩溃与 16 KB 页兼容

- 采集会话迁移到 MediaProjectionService 前台服务
- 修正 libopus JNI 符号名,加载失败时回退 MediaCodec
- .so 按 16 KB 页对齐,兼容 Android 15+ 设备
- 签名配置外置到 config.gradle(已忽略,不再入库)
- 心跳与传输改到后台线程,补充 Gradle wrapper
This commit is contained in:
tongtong committed 2026-11-26 21:22:53 +08:00
1 parent d7a65b976a
commit b89a65993c
13 files changed
+680 -98

No files matched your search

+8 -24
View File
@@ -3,6 +3,11 @@ plugins {
id("org.jetbrains.kotlin.android")
}
val configFile = rootProject.file("config.gradle")
if (configFile.exists()) {
apply(from = configFile)
}
android {
namespace = "com.ttstd.lancast.receiver"
compileSdk = 35
@@ -15,41 +20,20 @@ android {
versionName = "0.1.0"
}
signingConfigs {
create("keypub") {
storeFile = file("D:/TongTongStudio/TTSTD/keypub.jks")
storePassword = "123456"
keyAlias = "publickey"
keyPassword = "123456"
}
create("crosshatch") {
storeFile = file("D:/TongTongStudio/TTSTD/AospCrosshatch.keystore")
storePassword = "Fan1996"
keyAlias = "AospCrosshatch"
keyPassword = "Fan1996"
}
create("zhanxun") {
storeFile = file("D:/TongTongStudio/TTSTD/zhanxun.keystore")
storePassword = "123456"
keyAlias = "zhanxun"
keyPassword = "123456"
}
}
// 按签名划分变体:aosp/zhanxun 为系统签名,neutral 为普通(中性)签名。
flavorDimensions += "signature"
productFlavors {
create("aosp") {
dimension = "signature"
signingConfig = signingConfigs.getByName("crosshatch")
signingConfig = signingConfigs.findByName("crosshatch")
}
create("zhanxun") {
dimension = "signature"
signingConfig = signingConfigs.getByName("zhanxun")
signingConfig = signingConfigs.findByName("zhanxun")
}
create("neutral") {
dimension = "signature"
signingConfig = signingConfigs.getByName("keypub")
signingConfig = signingConfigs.findByName("keypub")
}
}
@@ -21,6 +21,12 @@
</intent-filter>
</activity>
<service
android:name=".MediaProjectionService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaProjection" />
<service
android:name=".input.LancastAccessibilityService"
android:exported="false"
@@ -6,6 +6,14 @@ add_library(ttstd_opus SHARED opus_jni.cpp)
find_library(log-lib log)
target_link_libraries(ttstd_opus ${log-lib})
# Android 15+ 的 16 KB 页设备要求 .so 的 LOAD 段按 16 KB 对齐。
# NDK r27 默认仍是 4 KB,NDK r28+ 才默认 16 KB,因此这里显式指定,
# 避免安装时报 "not compatible with 16 KB devices"。
target_link_options(ttstd_opus PRIVATE
-Wl,-z,max-page-size=16384
-Wl,-z,common-page-size=16384
)
# TODO(libopus): 将 opus 源码加入后,取消下面注释并启用 native 编码:
# add_subdirectory(opus)
# target_link_libraries(ttstd_opus opus)
@@ -4,13 +4,16 @@
// 接入 libopus 源码后改为 1,Kotlin 侧会自动切换到 native 编码器。
#define OPUS_NATIVE_AVAILABLE 0
// 注意:JNI 符号必须与 Kotlin 侧 external fun 的名称完全一致。
// OpusNative.kt 声明的是 nativeIsAvailable / nativeCreateEncoder /
// nativeDestroyEncoder / nativeEncode,因此这里不能省略 "native" 前缀。
extern "C" JNIEXPORT jboolean JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_isAvailable(JNIEnv*, jclass) {
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeIsAvailable(JNIEnv*, jclass) {
return OPUS_NATIVE_AVAILABLE == 1 ? JNI_TRUE : JNI_FALSE;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_createEncoder(
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeCreateEncoder(
JNIEnv*, jclass, jint, jint, jint) {
if (OPUS_NATIVE_AVAILABLE != 1) return 0;
// TODO(libopus): return reinterpret_cast<jlong>(opus_encoder_create(...));
@@ -18,12 +21,13 @@ Java_com_ttstd_lancast_receiver_encode_OpusNative_createEncoder(
}
extern "C" JNIEXPORT void JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_destroyEncoder(JNIEnv*, jclass, jlong) {
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeDestroyEncoder(
JNIEnv*, jclass, jlong) {
// TODO(libopus): opus_encoder_destroy(reinterpret_cast<OpusEncoder*>(handle));
}
extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_ttstd_lancast_receiver_encode_OpusNative_encode(
Java_com_ttstd_lancast_receiver_encode_OpusNative_nativeEncode(
JNIEnv* env, jclass, jlong, jbyteArray) {
if (OPUS_NATIVE_AVAILABLE != 1) return nullptr;
// TODO(libopus): 调用 opus_encode 生成 OPUS 包并返回 ByteArray 数组。
@@ -8,7 +8,6 @@ import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.ttstd.lancast.receiver.session.PairingCode
import com.ttstd.lancast.receiver.session.TlsSession
import java.net.NetworkInterface
@@ -19,7 +18,6 @@ class MainActivity : Activity() {
private const val FINGERPRINT = "sha256:ab12cd34ef567890"
}
private var session: ReceiverSession? = null
private lateinit var status: TextView
private lateinit var hostInput: EditText
private lateinit var signalingInput: EditText
@@ -27,7 +25,9 @@ class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
status = TextView(this).apply { text = "状态:未开始" }
status = TextView(this).apply {
text = if (MediaProjectionService.isRunning) "状态:采集中" else "状态:未开始"
}
hostInput = EditText(this).apply {
hint = "主控端 IP"
setText("192.168.1.5")
@@ -59,8 +59,7 @@ class MainActivity : Activity() {
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
stop.setOnClickListener {
session?.stop()
session = null
MediaProjectionService.stop(this)
status.text = "状态:已停止"
}
}
@@ -68,29 +67,12 @@ class MainActivity : Activity() {
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return
val manager = getSystemService(MediaProjectionManager::class.java)
val projection = manager.getMediaProjection(resultCode, data)
if (projection == null) {
Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show()
return
}
session = ReceiverSession(
context = this,
projection = projection,
host = hostInput.text.toString().trim(),
signalingUrl = signalingInput.text.toString().trim(),
certificatePem = "",
)
session?.start()
val host = hostInput.text.toString().trim()
val signalingUrl = signalingInput.text.toString().trim()
MediaProjectionService.start(this, resultCode, data, host, signalingUrl)
status.text = "状态:采集中 · 指纹 ${TlsSession.sha256Hex(FINGERPRINT.toByteArray()).take(16)}"
}
override fun onDestroy() {
session?.stop()
session = null
super.onDestroy()
}
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
@@ -0,0 +1,193 @@
package com.ttstd.lancast.receiver
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.widget.Toast
class MediaProjectionService : Service() {
companion object {
private const val TAG = "MediaProjectionService"
private const val CHANNEL_ID = "media_projection_service_channel"
private const val NOTIFICATION_ID = 1001
const val ACTION_START = "com.ttstd.lancast.receiver.action.START"
const val ACTION_STOP = "com.ttstd.lancast.receiver.action.STOP"
const val EXTRA_RESULT_CODE = "extra_result_code"
const val EXTRA_DATA = "extra_data"
const val EXTRA_HOST = "extra_host"
const val EXTRA_SIGNALING_URL = "extra_signaling_url"
@Volatile
var isRunning = false
private set
fun start(context: Context, resultCode: Int, data: Intent, host: String, signalingUrl: String) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_START
putExtra(EXTRA_RESULT_CODE, resultCode)
putExtra(EXTRA_DATA, data)
putExtra(EXTRA_HOST, host)
putExtra(EXTRA_SIGNALING_URL, signalingUrl)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
}
fun stop(context: Context) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_STOP
}
context.startService(intent)
}
}
private var session: ReceiverSession? = null
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START -> {
val resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
val data: Intent? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra(EXTRA_DATA)
}
val host = intent.getStringExtra(EXTRA_HOST) ?: ""
val signalingUrl = intent.getStringExtra(EXTRA_SIGNALING_URL) ?: ""
if (resultCode != 0 && data != null) {
startForegroundServiceWithNotification()
startProjectionSession(resultCode, data, host, signalingUrl)
} else {
stopSelf()
}
}
ACTION_STOP -> {
stopProjectionSession()
stopSelf()
}
}
return START_NOT_STICKY
}
private fun startForegroundServiceWithNotification() {
val notification = createNotification()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
)
} else {
startForeground(NOTIFICATION_ID, notification)
}
}
private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) {
stopProjectionSession()
try {
val manager = getSystemService(MediaProjectionManager::class.java)
val projection = manager.getMediaProjection(resultCode, data)
if (projection == null) {
Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show()
stopSelf()
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
projection.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
Log.i(TAG, "MediaProjection session stopped by system")
stopProjectionSession()
stopSelf()
}
}, Handler(Looper.getMainLooper()))
}
session = ReceiverSession(
context = this,
projection = projection,
host = host,
signalingUrl = signalingUrl,
certificatePem = "",
)
session?.start()
isRunning = true
} catch (e: Exception) {
Log.e(TAG, "Failed to start MediaProjection session", e)
Toast.makeText(this, "启动屏幕投影失败: ${e.message}", Toast.LENGTH_SHORT).show()
stopSelf()
}
}
private fun stopProjectionSession() {
session?.stop()
session = null
isRunning = false
}
override fun onDestroy() {
stopProjectionSession()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
@Suppress("DEPRECATION")
stopForeground(true)
}
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"屏幕投屏服务",
NotificationManager.IMPORTANCE_LOW
).apply {
description = "保持屏幕捕获服务在后台运行"
}
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
}
private fun createNotification(): Notification {
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
@Suppress("DEPRECATION")
Notification.Builder(this)
}
return builder
.setContentTitle("Lancast 投屏服务")
.setContentText("屏幕投屏服务正在运行中")
.setSmallIcon(android.R.drawable.ic_menu_camera)
.setOngoing(true)
.build()
}
}
@@ -1,36 +1,42 @@
package com.ttstd.lancast.receiver.discovery
import android.os.Handler
import android.os.Looper
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class ReceiverAnnouncer(
private val signalingUrl: String,
private val device: AnnouncedDevice,
) {
private val handler = Handler(Looper.getMainLooper())
private var runnable: Runnable? = null
private var executor: ScheduledExecutorService? = null
private var future: ScheduledFuture<*>? = null
@Volatile
private var registered = false
fun start() {
if (runnable != null) return
runnable = object : Runnable {
override fun run() {
if (future != null) return
val exec = Executors.newSingleThreadScheduledExecutor()
executor = exec
future = exec.scheduleWithFixedDelay({
try {
val path = if (registered) "/heartbeat" else "/register"
post(path, body())
registered = true
handler.postDelayed(this, 15_000)
} catch (_: Exception) {
}
}
handler.post(runnable!!)
}, 0, 15, TimeUnit.SECONDS)
}
fun stop() {
runnable?.let { handler.removeCallbacks(it) }
runnable = null
future?.cancel(true)
future = null
executor?.shutdownNow()
executor = null
registered = false
}
@@ -1,30 +1,66 @@
package com.ttstd.lancast.receiver.encode
import android.util.Log
/** libopus JNI 通道。native 库未接入源码时 isAvailable 为 false,由 MediaCodec 承接。 */
object OpusNative {
private const val TAG = "OpusNative"
@Volatile
private var loaded = true
init {
try {
System.loadLibrary("ttstd_opus")
} catch (error: UnsatisfiedLinkError) {
loaded = false
Log.w(TAG, "libttstd_opus 加载失败,回退 MediaCodec", error)
}
}
val isAvailable: Boolean
get() {
if (!loaded) return false
return try {
nativeIsAvailable()
} catch (error: UnsatisfiedLinkError) {
// 库存在但 JNI 符号缺失时不能让进程崩溃,直接永久回退。
loaded = false
Log.w(TAG, "JNI 符号缺失,回退 MediaCodec", error)
false
}
}
fun createEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long {
if (!isAvailable) return 0L
return try {
nativeCreateEncoder(sampleRate, channels, bitrate)
} catch (error: UnsatisfiedLinkError) {
loaded = false
Log.w(TAG, "nativeCreateEncoder 不可用,回退 MediaCodec", error)
0L
}
}
fun destroyEncoder(handle: Long) {
if (handle == 0L) return
try {
nativeDestroyEncoder(handle)
} catch (_: UnsatisfiedLinkError) {
loaded = false
}
}
val isAvailable: Boolean
get() = loaded && nativeIsAvailable()
fun createEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long =
if (isAvailable) nativeCreateEncoder(sampleRate, channels, bitrate) else 0L
fun destroyEncoder(handle: Long) {
if (handle != 0L) nativeDestroyEncoder(handle)
fun encode(handle: Long, pcm16: ByteArray): Array<ByteArray>? {
if (handle == 0L) return null
return try {
nativeEncode(handle, pcm16)
} catch (_: UnsatisfiedLinkError) {
loaded = false
null
}
}
fun encode(handle: Long, pcm16: ByteArray): Array<ByteArray>? =
if (handle != 0L) nativeEncode(handle, pcm16) else null
private external fun nativeIsAvailable(): Boolean
private external fun nativeCreateEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long
private external fun nativeDestroyEncoder(handle: Long)
@@ -1,6 +1,7 @@
package com.ttstd.lancast.receiver.session
import android.media.MediaCodec
import android.util.Log
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector
@@ -50,32 +51,41 @@ class ReceiverTransport(
val keyEstablished: Boolean get() = keys != null
fun start() {
val raw = Socket().apply {
tcpNoDelay = true
soTimeout = 5000
connect(InetSocketAddress(host, controlPort), 5000)
executor.execute {
try {
val raw = Socket().apply {
tcpNoDelay = true
soTimeout = 5000
connect(InetSocketAddress(host, controlPort), 5000)
}
socket = raw
output = DataOutputStream(raw.outputStream)
val input = DataInputStream(raw.inputStream)
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
output?.write(crypto.publicBytes)
output?.flush()
val peerPublic = ByteArray(65)
input.readFully(peerPublic)
keys = crypto.deriveKeys(peerPublic)
udp = DatagramSocket()
running = true
readLoop(input)
} catch (e: Exception) {
Log.e("ReceiverTransport", "Failed to connect or handshake", e)
close()
}
}
socket = raw
output = DataOutputStream(raw.outputStream)
val input = DataInputStream(raw.inputStream)
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
output?.write(crypto.publicBytes)
output?.flush()
val peerPublic = ByteArray(65)
input.readFully(peerPublic)
keys = crypto.deriveKeys(peerPublic)
udp = DatagramSocket()
running = true
executor.execute { readLoop(input) }
}
fun sendControl(event: ControlEvent) {
val key = keys?.control ?: return
if (!running) return
val frame = ControlFrames.encode(event, sequence++)
writeFrame(crypto.encodeControlFrame(frame, key))
executor.execute {
val key = keys?.control ?: return@execute
if (!running) return@execute
val frame = ControlFrames.encode(event, sequence++)
writeFrame(crypto.encodeControlFrame(frame, key))
}
}
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
@@ -172,6 +182,7 @@ class ReceiverTransport(
writeFrame(crypto.encodeControlFrame(frame, controlKey))
}
@Synchronized
private fun writeFrame(frame: ByteArray) {
try {
output?.write(frame)
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega