2016-04-23 150 views
2

我想檢測按下後退按鈕服務。我剛剛試過這段代碼,但沒有顯示任何日誌。有人可以解釋我爲什麼嗎?我該怎麼做才能使它工作?檢測按鈕的後退按鈕

做的總體思路,這是從本教程http://www.kpbird.com/2013/03/android-detect-global-touch-event.html

public class MyService extends Service implements View.OnKeyListener{ 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     LinearLayout touchLayout = new LinearLayout(this); 
     // set layout width 30 px and height is equal to full screen 
     LayoutParams lp = new LayoutParams(30, LayoutParams.MATCH_PARENT); 
     touchLayout.setLayoutParams(lp); 
     touchLayout.setBackgroundColor(Color.RED); 
     touchLayout.setOnKeyListener(this); 
     WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); 
     // set layout parameter of window manager 
     WindowManager.LayoutParams mParams = new WindowManager.LayoutParams(
       30, // width of layout 30 px 
       WindowManager.LayoutParams.MATCH_PARENT, // height is equal to full screen 
       WindowManager.LayoutParams.TYPE_PHONE, // Type Phone, These are non-application windows providing user interaction with the phone (in particular incoming calls). 
       WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // this window won't ever get key input focus 
       PixelFormat.TRANSLUCENT); 
     mParams.gravity = Gravity.LEFT | Gravity.TOP; 

     mWindowManager.addView(touchLayout, mParams); 
    } 

    @Override 
    public boolean onKey(View v, int keyCode, KeyEvent event) { 
     if (keyCode == KeyEvent.KEYCODE_BACK){ 
      Log.v("Point","KeyCode_Back"); 
      return false; 
     } 
     return false; 
    } 
} 

回答

1

你的服務是不是一個視圖拍攝,實施View.OnKeyListener不提供您所需的功能。

服務旨在成爲在應用程序的後臺運行的「無UI的活動」。您可以使用綁定器/廣播與您的服務進行通信,但UI交互最好留給活動/片段。

附件:
我想你正在試圖建立一個覆蓋像你在評論中發佈的鏈接。本教程是從2013年開始的,所以事情已經改變。

一般來說,Android系統不贊成應用程序beheaviour像下面描述的方法。像這樣的編碼進入被認爲是惡意軟件的類別Lockscreen/Kiosk-App行爲。

如果你想在你的應用程序內完成一個小菜單,你可以做到這一點,而不使用這樣的服務。在應用程序外部,您仍然可以使用小部件,這些小部件比在屏幕上硬編碼更方便用戶使用。

+0

@ r%c3%bcdiger我試着做這樣的事情http://www.kpbird.com/2013/03/android-detect-global-touch-event.html –

+0

根據你的編輯我的答案鏈接 –