Запросить программную клавишу "Назад" программно?
Я знаю, что можно переписать функциональность Back Button на Android, но мне было интересно, есть ли способ или что-нибудь, что я мог бы назвать, что бы функционально сделать то же самое, что нажать кнопку аппаратного обеспечения.
Ответы
Ответ 1
Вы можете отправить кнопку "Назад" в систему, как показано ниже.
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
Или вы можете переопределить кнопку "Назад" и нажать
finish();
в вашей деятельности. Это в основном делает то же самое, что и общая кнопка возврата.
Ответ 2
Просто вызовите this.onBackPressed();
в Activity.
Ответ 3
Если вы хотите просто нажать кнопку аппаратного обеспечения,
создать сервис, расширенный от 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)
}
}
Вызов doAction()
, где требуется действие
Добавить в 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" />
для более подробной информации смотрите https://developer.android.com/guide/topics/ui/accessibility/services.html