Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate home, back, menu, search, task and volume buttons?

I want to simulate all physical buttons of our Android devices.

So is there a way to simulate:

  • BACK BUTTON
  • HOME BUTTON
  • MENU BUTTON
  • SEARCH BUTTON
  • TASK BUTTON
  • VOLUME (+ AND -) BUTTONS
like image 969
Meroelyth Avatar asked Dec 14 '12 09:12

Meroelyth


2 Answers

Create a KeyEvent and publish it.

KeyEvent kdown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
Activity.dispatchKeyEvent(kdown);
KeyEvent kup = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
Activity.dispatchKeyEvent(kup);
like image 142
Aleksander Gralak Avatar answered Oct 06 '22 00:10

Aleksander Gralak


You can simulate pressing buttons even your app is closed, but you'll need Accessibility permission:

Create service extended from AccessibilityService:

class ExampleAccessService:AccessibilityService() {
    override fun onInterrupt() {
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
    }
    
    fun doAction(){
        performGlobalAction(GLOBAL_ACTION_RECENTS)
//        performGlobalAction(GLOBAL_ACTION_BACK)
//        performGlobalAction(GLOBAL_ACTION_HOME)
//        performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)
//        performGlobalAction(GLOBAL_ACTION_POWER_DIALOG)
//        performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS)
//        performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN)
    }
}

Call doAction() where you want action

Add to Manifest:

<application
...
    <service
        android:name=".ExampleAccessService"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:label="Name of servise" // it will be viewed in Settings->Accessibility->Services
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService"/>
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/accessibility_service_config"/>
    </service>
...
</application>

accessibility_service_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFeedbackType="feedbackAllMask"
    android:accessibilityFlags="flagDefault"
    android:canRetrieveWindowContent="false"
    android:description="your description"
    android:notificationTimeout="100"
    android:packageNames="your app package, ex: ex: com.example.android"
    android:settingsActivity="your settings activity ex: com.example.android.MainActivity" />

for more info look at https://developer.android.com/guide/topics/ui/accessibility/services.html

like image 34
Evgenii Vorobei Avatar answered Oct 06 '22 00:10

Evgenii Vorobei