如何在启动时对应用程序进行编程以关闭并自动打开主屏幕 (Launcher) (Wear OS)

How to program an application on launch to close and automatically open the home screen (Launcher) (Wear OS)

我是一般编程的初学者,我从来没有在 Android Studio 中编程,所以我可能做错了所有事情。

我只是想为我的 WearOS 3(基于 Android 11)手表制作一个非常简单的应用程序。

从任何区域(apk)启动应用程序时,我希望它打开主屏幕(默认启动器)。而已。它根本不需要 UI。

这是我目前所知道的,但我相信它陷入了循环。程序运行但随后崩溃,调试没有提供有关崩溃原因的信息:

package com.example.returntohome

import android.app.Activity
import android.content.Intent
import android.os.Bundle


class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val startMain = Intent(Intent.ACTION_MAIN)
        startMain.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startMain.addCategory(Intent.CATEGORY_HOME)
        moveTaskToBack(true)

    }
}

我正在使用 Kotlin。我可以尝试解决这个问题吗?

你的意图是正确的。您只是缺少实际启动意图的最后一点。

val startMain = Intent(Intent.ACTION_MAIN)
startMain.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startMain.addCategory(Intent.CATEGORY_HOME)
startActivity(startMain) // <- Start the intent