如何在服务中听取主页密钥?

时间:2016-05-30 07:20:21

标签: android key android-service listener android-homebutton

我创建了一个简单的应用程序演示,并在我的服务类中创建了一个布局。 在服务类中,我创建了一个布局,当用户点击主页键时我需要隐藏这个布局。

我找到了示例here并实施了setOnKeyListenersetOnFocusChangeListener,但点击主页按钮时却没有。

我的服务类代码:

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT
        );
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.service_layout, null);
        view.setFocusable(true);
        wm.addView(view, params);

        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("FROM", "HOME OR OTHER KEY PRESSED");
                return false;
            }
        });

        view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.i("FROM", "HOME OR OTHER KEY PRESSED");
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

收听广播:

public class HomeWatcherReceiver extends BroadcastReceiver {
    private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
    private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {

            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

            if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {

                //homekey

            }

        }
    }
}