Android 애플리케이션에서 Google 번역 열기

15391 단어 android
이 게시물에서는 프로그래밍 방식으로 다른 Android 애플리케이션에서 Google 번역을 열고 번역할 텍스트를 전달하는 방법을 보여줍니다.

예를 들어 일부 텍스트를 표시하고 "번역"버튼을 제공하는 화면을 사용하겠습니다.



다음은 소스 코드입니다.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TranslateTestTheme {
                MainScreen(
                    title = "Dog",
                    body = dogDescription,
                    onTranslateClick = { openGoogleTranslate(dogDescription) },
                )
            }
        }
    }
}

@Composable
private fun MainScreen(
    title: String,
    body: String,
    onTranslateClick: () -> Unit,
) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = title) },
                actions = {
                    IconButton(onClick = onTranslateClick) {
                        Icon(Icons.Default.GTranslate, contentDescription = "Translate")
                    }
                }
            )
        },
        content = {
            Text(
                text = body,
                style = MaterialTheme.typography.body2,
                modifier = Modifier.padding(16.dp),
            )
        },
    )
}


핵심 부분은 다음 콜백입니다: onTranslateClick = { openGoogleTranslate(dogDescription) } .

Intent.ACTION_PROCESS_TEXT로 Google 번역 시작


openGoogleTranslate 메서드를 살펴보겠습니다.

fun Context.openGoogleTranslate(text: String) {
    val intent = Intent()
        .setAction(Intent.ACTION_PROCESS_TEXT)
        .setType("text/plain")
        .putExtra(Intent.EXTRA_PROCESS_TEXT, text)
        .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true)
    startActivity(intent)
}

Activity 인텐트 필터에 등록된 모든 Intent.ACTION_PROCESS_TEXT를 엽니다. Google 번역 앱은 이러한Activity를 제공하므로 언급된 메소드가 호출될 때 열리는 후보 중 하나입니다.

그러나 일부 사용자에게는 Google 번역 애플리케이션이 설치되어 있지 않다는 점을 기억하는 것이 중요합니다. 일부 사용자의 장치에는 처리하는 더 많은 응용 프로그램이 있습니다Intent.ACTION_PROCESS_TEXT.

두 번째 경우 Android는 다음 대화 상자를 표시합니다.



설치된 인텐트를 처리할 애플리케이션이 없는 경우 ActivityNotFoundException 호출 시 startActivity가 발생합니다. 이 경우는 try/catch 블록으로 처리할 수 있습니다.

try {
    startActivity(intent)
} catch (e: ActivityNotFoundException) {
    // TODO: Show error
}


Google 번역이 설치되어 있는지 확인



구글 번역이 설치되어 있어야만 "번역"버튼이 표시되면 좋을 것 같습니다. 다음 코드를 사용하여 존재 여부를 확인할 수 있습니다.

fun Context.queryProcessTextActivities(): List<ResolveInfo> {
    val intent = Intent()
        .setAction(Intent.ACTION_PROCESS_TEXT)
        .setType("text/plain")
    return packageManager.queryIntentActivities(intent, 0)
}

fun Context.isGoogleTranslateInstalled() = queryProcessTextActivities()
    .any { it.activityInfo.packageName == "com.google.android.apps.translate" }

queryIntentActivities가 모든 Android 버전에서 올바르게 작동하도록 하려면 다음 조각을 AndroidManifest.xml에 추가해야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <application ...>
        ...
    </application>
    <queries>
        <intent>
            <action android:name="android.intent.action.PROCESS_TEXT" />
            <data android:mimeType="text/plain" />
        </intent>
    </queries>
</manifest>


Google 번역 직접 실행



또한 인텐트를 처리할 다른 애플리케이션이 있는지 여부에 관계없이 Google 번역이 설치되어 있는지 확인할 수 있습니다.

이를 위해 다음 코드를 사용할 수 있습니다.

fun Context.queryProcessTextActivities(): List<ResolveInfo> {
    val intent = Intent()
        .setAction(Intent.ACTION_PROCESS_TEXT)
        .setType("text/plain")
    return packageManager.queryIntentActivities(intent, 0)
}

fun Context.googleTranslateActivityInfo() = queryProcessTextActivities()
    .firstOrNull { it.activityInfo.packageName == "com.google.android.apps.translate" }
    ?.activityInfo

fun Context.openGoogleTranslate(activity: ActivityInfo, text: String) {
    val intent = Intent()
        .setAction(Intent.ACTION_PROCESS_TEXT)
        .setType("text/plain")
        .putExtra(Intent.EXTRA_PROCESS_TEXT, text)
        .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true)
        // Following line makes sure only Google Translate app will be launched
        .setClassName(activity.packageName, activity.name)
    try {
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // TODO: Show error
    }
}


다음 링크에서 전체 Kotlin 코드를 찾을 수 있습니다. https://gist.github.com/pchmielowski/d236f06f168c05efa3f5b26f1e2f0af9

좋은 웹페이지 즐겨찾기