Android analog remote home click

Generally speaking, the following methods are mostly used to simulate the home button:

  val i = Intent(Intent.ACTION_MAIN)
  i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
  i.addCategory(Intent.CATEGORY_HOME)
  startActivity(i)

The problem is that our application runs on a set-top box, and two launchers are installed in the box. After the above code is executed, the launcher selection interface will pop up. The test found that clicking the home button on the remote control does not pop up the launcher selection interface, so use Instrumentation instead:

 Thread {
            Thread.sleep(400)
            println("模拟Home键点击")
            var ins = Instrumentation()
            ins.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME)
        }.start()

Note: sendKeyDownUpSync cannot be called from the main thread.
If you run the above code, an error may be reported, prompting that you need to apply for permission:

<uses-permission android:name="android.permission.INJECT_EVENTS"/>

And apply for the system application android:sharedUserId="android.uid.system" But this permission can only be applied for the system application, so the app signed by the system is required.

Guess you like

Origin blog.csdn.net/weixin_40652755/article/details/122594897