0

I created a simple app demo and created a layout in my service class. In the service class, I created a layout and I need to hide this layout when the user clicks on the home key.

I found sample here and implemented setOnKeyListener and setOnFocusChangeListener but not happen when clicked on home button.

My service class code:

    @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");
            }
        });
    }
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Hamed Hosseini
  • 182
  • 2
  • 13

1 Answers1

2

Listen to the broadcast:

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

            }

        }
    }
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Alan
  • 21
  • 3