How to deal with all keyevents when added a view with WindowManager? - java

Problem is on a service view back button is giving me a response but Home and Recent Apps button is not triggering
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_HOME: //Not getting
minimizeApp();
return true;
case KeyEvent.KEYCODE_BACK: //getting
finish(false);
return true;
case KeyEvent.KEYCODE_APP_SWITCH: //Not getting
//minimizeApp();
return true;
}
return true;
}
in the same service, I have tried to add and remove different flags but can't gets what I want.
mLayoutParams =new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON|
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
|WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
,
PixelFormat.TRANSLUCENT);
I am getting Back pressed but I want to catch Event of home and recent app pressed.

Updated
I got the solution
li = LayoutInflater.from(this);
LinearLayout lia= new LinearLayout(this) {
//home or recent button
public void onCloseSystemDialogs(String reason) {
if (reason.equals("homekey")){
finisha(false);
}
if (reason.equals("recentapps")){
finisha(false);
}
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
|| event.getKeyCode() == KeyEvent.KEYCODE_APP_SWITCH
|| event.getKeyCode() == KeyEvent.KEYCODE_HOME
) {
//The Code Want to Perform.
// return true;
}
if (event.getKeyCode() == KeyEvent.KEYCODE_HOME){
}
if (event.getKeyCode() == KeyEvent.KEYCODE_APP_SWITCH){
}
return super.dispatchKeyEvent(event);
}
};
lia.setFocusable(true);
final View root = (View) li.inflate(R.layout.layout_alias_locker, lia);

Related

how to disable or hide the right and left arrow from keyboard with ViewPager android

I am trying to disable left and right on the keyboard with this code but viewPager on the press of left and right button change the state of the pager.
edComment.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS
|| actionId == EditorInfo.IME_FLAG_NAVIGATE_NEXT
|| actionId == EditorInfo.IME_ACTION_PREVIOUS
|| actionId == EditorInfo.IME_ACTION_NEXT
) {
return false;
}
// Return true if you have consumed the action, else false.
return false;
}
});
You can extend the ViewPager and override the arrowScroll method like this:
public class Wizard extends ViewPager {
#Override
public boolean arrowScroll(int direction) {
// Never allow pressing keyboard arrows to switch between pages
return false;
}
}
The keyboard app can show whatever keys it wants. There is no way to force it not to show certain buttons, and even if there was another keyboard wouldn't follow the same rules.
According to #Gabe Sechan button are not hide or disable so I am doing like that
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.i("your tag", "Keycode: " + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
Log.e("Click","left");
/* for (int n = 0; n < count; n++) {
setCurrentPage(arrayListView.get(n + 1));
}*/
pager.setCurrentItem(getItem(+1), true);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
Log.e("Click","right");
pager.setCurrentItem(getItem(-1), true);
return true;
case KeyEvent.KEYCODE_DPAD_UP:
Log.e("Click","up");
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
Log.e("Click","Down");
return true;
default:
return super.onKeyUp(keyCode, event);
}
}

Weird if/else behavior Android

I'm trying to cacth done action which comes from softkeyboard. My code is like this;
private TextView.OnEditorActionListener getDoneListener() {
return new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
nextPage();
return true;
}
else {
return false;
}
}
};
}
However even though IDE evaluates "(actionId == EditorInfo.IME_ACTION_DONE)"as true, it's not calling nextPage(), returning false instead. If I cast expression like this, it works fine.
private TextView.OnEditorActionListener getDoneListener() {
return new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((boolean)(actionId == EditorInfo.IME_ACTION_DONE)) {
processPayment();
return true;
}
else {
return false;
}
}
};
}
Any idea what can cause this?

ImageView MotionEvent if two pointer, stop ACTION_UP

In my activity I have an ImageView. It has pinch-zoom feature.
When I touch on ImageView I show thumbnails layout.
But when I pinch on ImageView thumbnail layout shows. I want to block it?
How can I do it?
Here is my code to show thumbnail layout:
image.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Boolean openThumbnails=true;
if(event.getAction() == MotionEvent.ACTION_UP && openThumbnails){
Log.e("event.getAction()", "MotionEvent.ACTION_UP");
if(thumbnailsLayout.getVisibility()==View.GONE && header.getVisibility()==View.GONE && openThumbnails){
thumbnailsLayout.setVisibility(View.VISIBLE);
header.setVisibility(View.VISIBLE);
header.bringToFront();
}
else{
thumbnailsLayout.setVisibility(View.GONE);
header.setVisibility(View.GONE);
}
}
else if(event.getAction() == MotionEvent.ACTION_DOWN){
Log.e("event.getAction()", "MotionEvent.ACTION_DOWN");
return true;
}
else if(event.getAction()==MotionEvent.ACTION_MOVE){
Log.e("openThumbnails before", openThumbnails.toString());
openThumbnails=false;
Log.e("openThumbnails and after", openThumbnails.toString());
}
return false;
}
});
Your openThumbnails is always true. You set it at the start of method. Every touch event (e.g. Action_up, action_move) you set openThumbnail to true. That's why you always show it.
image.setOnTouchListener(new OnTouchListener() {
Boolean openThumbnails=true;
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP && openThumbnails){
Log.e("event.getAction()", "MotionEvent.ACTION_UP");
if(thumbnailsLayout.getVisibility()==View.GONE && header.getVisibility()==View.GONE && openThumbnails){
thumbnailsLayout.setVisibility(View.VISIBLE);
header.setVisibility(View.VISIBLE);
header.bringToFront();
}
else{
thumbnailsLayout.setVisibility(View.GONE);
header.setVisibility(View.GONE);
}
}
else if(event.getAction() == MotionEvent.ACTION_DOWN){
Log.e("event.getAction()", "MotionEvent.ACTION_DOWN");
return true;
}
else if(event.getAction()==MotionEvent.ACTION_MOVE){
Log.e("openThumbnails before", openThumbnails.toString());
openThumbnails=false;
Log.e("openThumbnails and after", openThumbnails.toString());
}
return false;
}
});

Android: Probleme use keyboard enter button say “Search” and handle its click?

I want to add a search button on the keyboard input and the EditText and searches I proceeded as follows and I have them the following errors
recherche=(EditText)findViewById(R.id.recherche);
recherche.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
new DownloadTask().execute();
return true;
}
return false;
}
});
ERROR : The type new TextView.OnEditorActionListener(){} must implement the inherited abstract method
TextView.OnEditorActionListener.onEditorAction(TextView, int, KeyEvent)
ERROR : KeyEvent cannot be resolved to a type
Here is a sample of my code:
TextView.OnEditorActionListener enterListener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if ((keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (i == EditorInfo.IME_ACTION_DONE)) {
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
bQServer.performClick();
}
return false;
}
};
//etUserName.setOnEditorActionListener(enterListener);
etPassword.setOnEditorActionListener(enterListener);
You should be able to just change KeyEvent.KEYCODE_ENTER for KeyEvent.KEYCODE_SEARCH
i.e
TextView.OnEditorActionListener enterListener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if ((keyEvent != null && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_SEARCH)) {
new DownloadTask().execute();
return true;
}
return false;
}
};
recherche.setOnEditorActionListener(enterListener);
--Edit--
Make sure you have imported KeyEvent and onEditorActionListener
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;

Detecting a long press in Android

I am currently using onTouchEvent(MotionEvent event) { } to detect when the user presses my glSurfaceView is there a way to detect when a long click is made.
I'm guessing if I can't find much in the dev docs then it will be some sort of work around method. Something like registering ACTION_DOWN and seeing how long it is before ACTION_UP.
How do you detect long presses on Android using opengl-es?
GestureDetector is the best solution.
Here is an interesting alternative. In onTouchEvent on every ACTION_DOWN schedule a Runnable to run in 1 second. On every ACTION_UP or ACTION_MOVE, cancel scheduled Runnable. If cancelation happens less than 1s from ACTION_DOWN event, Runnable won't run.
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
Log.i("", "Long press!");
}
};
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView){
if(event.getAction() == MotionEvent.ACTION_DOWN)
handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
if((event.getAction() == MotionEvent.ACTION_MOVE)||(event.getAction() == MotionEvent.ACTION_UP))
handler.removeCallbacks(mLongPressed);
return super.onTouchEvent(event, mapView);
}
Try this:
final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(MotionEvent e) {
Log.e("", "Longpress detected");
}
});
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
};
I have a code which detects a click, a long click and movement.
It is fairly a combination of the answer given above and the changes i made from peeping into every documentation page.
//Declare this flag globally
boolean goneFlag = false;
//Put this into the class
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
goneFlag = true;
//Code for long click
}
};
//onTouch code
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(mLongPressed, 1000);
//This is where my code for movement is initialized to get original location.
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(mLongPressed);
if(Math.abs(event.getRawX() - initialTouchX) <= 2 && !goneFlag) {
//Code for single click
return false;
}
break;
case MotionEvent.ACTION_MOVE:
handler.removeCallbacks(mLongPressed);
//Code for movement here. This may include using a window manager to update the view
break;
}
return true;
}
I confirm it's working as I have used it in my own application.
I have created a snippet - inspired by the actual View source - that reliably detects long clicks/presses with a custom delay. But it's in Kotlin:
val LONG_PRESS_DELAY = 500
val handler = Handler()
var boundaries: Rect? = null
var onTap = Runnable {
handler.postDelayed(onLongPress, LONG_PRESS_DELAY - ViewConfiguration.getTapTimeout().toLong())
}
var onLongPress = Runnable {
// Long Press
}
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
boundaries = Rect(view.left, view.top, view.right, view.bottom)
handler.postDelayed(onTap, ViewConfiguration.getTapTimeout().toLong())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(onLongPress)
handler.removeCallbacks(onTap)
}
MotionEvent.ACTION_MOVE -> {
if (!boundaries!!.contains(view.left + event.x.toInt(), view.top + event.y.toInt())) {
handler.removeCallbacks(onLongPress)
handler.removeCallbacks(onTap)
}
}
}
return true
}
When you mean user presses, do you mean a click? A click is when the user presses down and then immediately lifts up finger. Therefore it is encompassing two onTouch Events. You should save the use of onTouchEvent for stuff that happens on the initial touch or the after release.
Thus, you should be using onClickListener if it is a click.
Your answer is analogous: Use onLongClickListener.
The solution by MSquare works only if you hold a specific pixel, but that's an unreasonable expectation for an end user unless they use a mouse (which they don't, they use fingers).
So I added a bit of a threshold for the distance between the DOWN and the UP action in case there was a MOVE action inbetween.
final Handler longPressHandler = new Handler();
Runnable longPressedRunnable = new Runnable() {
public void run() {
Log.e(TAG, "Long press detected in long press Handler!");
isLongPressHandlerActivated = true;
}
};
private boolean isLongPressHandlerActivated = false;
private boolean isActionMoveEventStored = false;
private float lastActionMoveEventBeforeUpX;
private float lastActionMoveEventBeforeUpY;
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
longPressHandler.postDelayed(longPressedRunnable, 1000);
}
if(event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
if(!isActionMoveEventStored) {
isActionMoveEventStored = true;
lastActionMoveEventBeforeUpX = event.getX();
lastActionMoveEventBeforeUpY = event.getY();
} else {
float currentX = event.getX();
float currentY = event.getY();
float firstX = lastActionMoveEventBeforeUpX;
float firstY = lastActionMoveEventBeforeUpY;
double distance = Math.sqrt(
(currentY - firstY) * (currentY - firstY) + ((currentX - firstX) * (currentX - firstX)));
if(distance > 20) {
longPressHandler.removeCallbacks(longPressedRunnable);
}
}
}
if(event.getAction() == MotionEvent.ACTION_UP) {
isActionMoveEventStored = false;
longPressHandler.removeCallbacks(longPressedRunnable);
if(isLongPressHandlerActivated) {
Log.d(TAG, "Long Press detected; halting propagation of motion event");
isLongPressHandlerActivated = false;
return false;
}
}
return super.dispatchTouchEvent(event);
}
The idea is creating a Runnable for execute long click in a future, but this execution can be canceled because of a click, or move.
You also need to know, when long click was consumed, and when it is canceled because finger moved too much. We use initialTouchX & initialTouchY for checking if the user exit a square area of 10 pixels, 5 each side.
Here is my complete code for delegating Click & LongClick from Cell in ListView to Activity with OnTouchListener:
ClickDelegate delegate;
boolean goneFlag = false;
float initialTouchX;
float initialTouchY;
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
Log.i("TOUCH_EVENT", "Long press!");
if (delegate != null) {
goneFlag = delegate.onItemLongClick(index);
} else {
goneFlag = true;
}
}
};
#OnTouch({R.id.layout})
public boolean onTouch (View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
initialTouchX = motionEvent.getRawX();
initialTouchY = motionEvent.getRawY();
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
handler.removeCallbacks(mLongPressed);
return true;
}
return false;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(mLongPressed);
if (goneFlag || Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
goneFlag = false;
return true;
}
break;
}
Log.i("TOUCH_EVENT", "Short press!");
if (delegate != null) {
if (delegate.onItemClick(index)) {
return false;
}
}
return false;
}
ClickDelegateis an interface for sending click events to the handler class like an Activity
public interface ClickDelegate {
boolean onItemClick(int position);
boolean onItemLongClick(int position);
}
And all what you need is to implement it in your Activity or parent Viewif you need to delegate the behavior:
public class MyActivity extends Activity implements ClickDelegate {
//code...
//in some place of you code like onCreate,
//you need to set the delegate like this:
SomeArrayAdapter.delegate = this;
//or:
SomeViewHolder.delegate = this;
//or:
SomeCustomView.delegate = this;
#Override
public boolean onItemClick(int position) {
Object obj = list.get(position);
if (obj) {
return true; //if you handle click
} else {
return false; //if not, it could be another event
}
}
#Override
public boolean onItemLongClick(int position) {
Object obj = list.get(position);
if (obj) {
return true; //if you handle long click
} else {
return false; //if not, it's a click
}
}
}
setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
longClick = false;
x1 = event.getX();
break;
case MotionEvent.ACTION_MOVE:
if (event.getEventTime() - event.getDownTime() > 500 && Math.abs(event.getX() - x1) < MIN_DISTANCE) {
longClick = true;
}
break;
case MotionEvent.ACTION_UP:
if (longClick) {
Toast.makeText(activity, "Long preess", Toast.LENGTH_SHORT).show();
}
}
return true;
}
});
Here is an approach, based on MSquare's nice idea for detecting a long press of a button, that has an additional feature: not only is an operation performed in response to a long press, but the operation is repeated until a MotionEvent.ACTION_UP message is received. In this case, the long-press and short-press actions are the same, but they could be different.
Note that, as others have reported, removing the callback in response to a MotionEvent.ACTION_MOVE message prevented the callback from ever getting executed since I could not keep my finger still enough. I got around that problem by ignoring that message.
private void setIncrementButton() {
final Button btn = (Button) findViewById(R.id.btn);
final Runnable repeater = new Runnable() {
#Override
public void run() {
increment();
final int milliseconds = 100;
btn.postDelayed(this, milliseconds);
}
};
btn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
increment();
v.postDelayed(repeater, ViewConfiguration.getLongPressTimeout());
} else if (e.getAction() == MotionEvent.ACTION_UP) {
v.removeCallbacks(repeater);
}
return true;
}
});
}
private void increment() {
Log.v("Long Press Example", "TODO: implement increment operation");
}
option: custom detector class
abstract public class
Long_hold
extends View.OnTouchListener
{
public#Override boolean
onTouch(View view, MotionEvent touch)
{
switch(touch.getAction())
{
case ACTION_DOWN: down(touch); return true;
case ACTION_MOVE: move(touch);
}
return true;
}
private long
time_0;
private float
x_0, y_0;
private void
down(MotionEvent touch)
{
time_0= touch.getEventTime();
x_0= touch.getX();
y_0= touch.getY();
}
private void
move(MotionEvent touch)
{
if(held_too_short(touch) {return;}
if(moved_too_much(touch)) {return;}
long_press(touch);
}
abstract protected void
long_hold(MotionEvent touch);
}
use
private double
moved_too_much(MotionEvent touch)
{
return Math.hypot(
x_0 -touch.getX(),
y_0 -touch.getY()) >TOLERANCE;
}
private double
held_too_short(MotionEvent touch)
{
return touch.getEventTime()-time_0 <DOWN_PERIOD;
}
where
TOLERANCE is the maximum tolerated movement
DOWN_PERIOD is the time one has to press
import
static android.view.MotionEvent.ACTION_MOVE;
static android.view.MotionEvent.ACTION_DOWN;
in code
setOnTouchListener(new Long_hold()
{
protected#Override boolean
long_hold(MotionEvent touch)
{
/*your code on long hold*/
}
});
I found one solution and it does not require to define runnable or other things and it's working fine.
var lastTouchTime: Long = 0
// ( ViewConfiguration.#.DEFAULT_LONG_PRESS_TIMEOUT =500)
val longPressTime = 500
var lastTouchX = 0f
var lastTouchY = 0f
view.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
lastTouchTime = SystemClock.elapsedRealtime()
lastTouchX = event.x
lastTouchY = event.y
return#setOnTouchListener true
}
MotionEvent.ACTION_UP -> {
if (SystemClock.elapsedRealtime() - lastTouchTime > longPressTime
&& Math.abs(event.x - lastTouchX) < 3
&& Math.abs(event.y - lastTouchY) < 3) {
Log.d(TAG, "Long press")
}
return#setOnTouchListener true
}
else -> {
return#setOnTouchListener false
}
}
}

Categories