AssimilateTranslate/app/src/main/java/com/assimilate/alltrans/viewui/MainActivity.kt
2024-07-11 17:54:19 +08:00

268 lines
8.5 KiB
Kotlin

package com.assimilate.alltrans.viewui
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.speech.RecognizerIntent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.assimilate.alltrans.MyApp
import com.assimilate.alltrans.R
import com.assimilate.alltrans.allservice.SusService
import com.assimilate.alltrans.common.Widget
import com.assimilate.alltrans.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private var launcher: ActivityResultLauncher<Intent>? = null
private lateinit var binding: ActivityMainBinding
private lateinit var lcm: LocalBroadcastManager
private lateinit var mediaProjectionManager: MediaProjectionManager
private val REQUEST_CODE_SCREEN_CAPTURE = 1001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(26, systemBars.top + 26, 26, systemBars.bottom)
insets
}
initSet()
initClick()
registerResult()
}
private fun registerResult() {
launcher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
val data = result.data
if (result.resultCode == RESULT_OK && data != null) {
val speech =
data.getStringArrayListExtra("android.speech.extra.RESULTS")?.get(0)
if (!TextUtils.isEmpty(speech)) {
binding.etText.setText(speech)
}
}
}
}
private fun startScreenCapture() {
val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
startActivityForResult(captureIntent, REQUEST_CODE_SCREEN_CAPTURE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SCREEN_CAPTURE && resultCode == Activity.RESULT_OK) {
startSusService(resultCode, data)
}
}
private fun startSusService(resultCode: Int, data: Intent?) {
val serviceIntent = Intent(this, SusService::class.java).apply {
putExtra("resultCode", resultCode)
putExtra("data", data)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent)
} else {
startService(serviceIntent)
}
}
private fun initView() {
binding.chSourceLanguage.text = MyApp.getSourceLanguage()
binding.chTargetLanguage.text = MyApp.getTargetLanguage()
}
private fun initSet() {
lcm = LocalBroadcastManager.getInstance(this)
// 监听EditText的文本变化
binding.etText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
// 根据EditText的内容显示或隐藏粘贴按钮
if (s.isNullOrEmpty()) {
binding.tvMainTrans.visibility = View.GONE
} else {
binding.tvMainTrans.visibility = View.VISIBLE
}
}
})
}
private fun initClick() {
binding.tvMainPhotoTrans.setOnClickListener {
startActivity(
Intent(this, StillImageActivity::class.java)
)
}
binding.tvMainVoice.setOnClickListener {
voiceToText()
toTextTransResult()
}
binding.tvMainPaste.setOnClickListener {
pasteFromClipboard(binding.etText)
toTextTransResult()
}
binding.tvMainTrans.setOnClickListener {
toTextTransResult()
}
binding.ivMainSetting.setOnClickListener {
startActivity(
Intent(this, SettingsActivity::class.java)
)
}
binding.chSourceLanguage.setOnClickListener {
startActivity(
Intent(this, LanguageChangeActivity::class.java)
)
}
binding.chTargetLanguage.setOnClickListener {
startActivity(
Intent(this, LanguageChangeActivity::class.java)
)
}
binding.ivMainHistory.setOnClickListener {
startActivity(
Intent(this, HistoryActivity::class.java)
)
}
binding.llQuickSet.setOnClickListener {
startActivity(
Intent(this, QuickSetActivity::class.java)
)
}
binding.ivQuickStart.setOnClickListener {
mediaProjectionManager =
getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
startScreenCapture()
val intent = Intent(this, SusService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}
}
private fun toTextTransResult() {
if (binding.etText.text.isEmpty()) {
return
}
val intent = Intent(this, TextResultActivity::class.java)
// 将字符串数据添加到Intent中
intent.putExtra("source_text", binding.etText.text.toString())
startActivity(intent)
binding.etText.text = null
}
// 语音转文本
private fun voiceToText() {
val speechIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
speechIntent.putExtra(
RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS,
5000
) // 设置5秒的静默时间
speechIntent.putExtra(
RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS,
5000
) // 设置5秒的可能完全静默时间
speechIntent.putExtra(
"android.speech.extra.LANGUAGE_MODEL",
MyApp.getSourceLanguage()
)
speechIntent.putExtra(
"android.speech.extra.LANGUAGE",
MyApp.getSourceLanguageCode()
)
speechIntent.putExtra(
"android.speech.extra.LANGUAGE_PREFERENCE",
MyApp.getSourceLanguage()
)
try {
launcher?.launch(speechIntent)
} catch (ea: ActivityNotFoundException) {
Widget.makeToast(this, "Something went wrong.")
}
}
// 粘贴文本
private fun pasteFromClipboard(etText: EditText) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
if (clipboard.hasPrimaryClip() && clipboard.primaryClipDescription!!.hasMimeType(
ClipDescription.MIMETYPE_TEXT_PLAIN
)
) {
val item = clipboard.primaryClip!!.getItemAt(0)
val text = item.text.toString()
if (text.isNotEmpty()) {
// 在EditText中显示粘贴的文本
etText.setText(text)
etText.requestFocus() // 获取焦点
}
}
}
override fun onResume() {
super.onResume()
initView()
}
override fun onDestroy() {
super.onDestroy()
if (null != launcher) {
launcher!!.unregister()
launcher = null
}
}
}