簡體   English   中英

檢測按下后退按鈕

[英]Detect press of back button

我想檢測在服務中按下后退按鈕。 我剛剛試過這段代碼,但它沒有顯示任何日志。 有人可以解釋我為什么嗎? 我應該怎么做才能讓它發揮作用?

這樣做的整個想法來自本教程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;
    }
}

您的服務不是視圖,實現 View.OnKeyListener 並不能提供您想要的功能。

服務旨在成為在應用程序后台運行的“沒有 UI 的活動”。 您可以使用 Binders/Broadcasts 與您的服務進行通信,但 UI 交互最好留給 Activity/Fragments。

附件:
我猜您正在嘗試像您在評論中發布的鏈接一樣構建一個疊加層。 這個教程是從 2013 年開始的,所以事情發生了變化。

一般來說,Android 系統不鼓勵應用程序行為,如以下描述的方法。 像這樣的編碼屬於被視為惡意軟件的鎖屏/信息亭應用行為類別。

如果你想在你的應用程序中完成一個小小的側邊菜單,你可以在不使用這樣的服務的情況下做得很好。 在您的應用程序之外,您仍然可以選擇使用小部件,這比在屏幕上硬編碼更友好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM