2012-07-31 87 views

回答

21

你可以後退按鈕按下發送到系統這樣

this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); 

或者你可以重寫後退按鈕按下並在您的活動呼籲

finish(); 

。這基本上和通用後退按鈕一樣。

+0

在我的代碼不工作...告訴我將其更改爲ACTION_DOWN,並KEYCODE_BACK不存在,那會我需要爲他們導入被發現? – JuiCe 2012-07-31 19:23:48

+1

嘗試使用KeyEvent.ACTION_DOWN和KeyEvent.KEYCODE_BACK :) – jimmithy 2012-07-31 19:26:36

+0

非常感謝你們。 – JuiCe 2012-07-31 19:29:10

12

只需在Activity中撥打this.onBackPressed();即可。

+0

這是一個很好的答案。 – VSG24 2016-08-24 20:11:16

+1

這是最好的答案,因爲簡單地調用完成不會像真正的後退按鈕那樣觸發onBackPressed。如果活動在那裏做了額外的事情,它會被錯過。 – Andrew 2016-12-23 03:51:54

+0

但是,如果活動上有任何對話,那麼它將關閉活動,而真正的按鈕不會這樣做。 – NehaK 2018-02-23 10:09:15

0

如果你想只是 「按」 硬件按鈕, 創建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) 
    } 
} 

呼叫您要行動

添加到ManifestdoAction()

<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> 

accessibili ty_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

相關問題