Android apps : Get button event in background - android

I create an Android app for a device without screen (not a phone). At startup my apps is launched and works correctly.
I try to catch the physical buttons event (down/up). It works but only one time when my apps starts. Then the events are not fire.
I have an idea : the apps is in the background and doesn't receive the events.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Context context = getApplicationContext();
//Start a service
Intent intent = new Intent(context,MainService.class);
context.startService(intent);
//finish();
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
//Send event to server
return true;
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
//Send event to server
return true;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
//Send event to server
return true;
}
}
Do you have an idea ? I suppose I am not the first person with this problem ...
Regards,

Found the solution: a second app was catching and blocking? the events. I have removed the apps and it's ok now.

Related

how get power button click event

I am trying capture power click in my android app, I was looking for any solution and I just find one with good results, It is when I detect screenOn/screenOff like this:
public class Receiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, PowerButtonService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
The problem in this method is that in my app I am looking for do it with screen Off, then it is not util for me.
I tryed this code also in my MainActivity but this doesn't work, debuging it, this the execution go inside when I push vol up or down but not when I push power key:
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Log.i("Main", "Dispath event power");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
Log.d("DISPATCH", "boton pulsado");
return true;
}
return super.dispatchKeyEvent(event);
}
I have the same problem in this one:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button down detected");
return true;
}
return false;
}
Could someone help me? thanks
Edit: I want to catch short key press
Sorry for my english

Android touch event on home screen not on any view

I am working on a Android Application project in which I am doing continuous task and when user click anywhere on home screen of phone I have to stop this work. Please anyone guide me how I can get touch event in my app so I can do some task. Any Broadcast for touch or any thing I can use. So that I can get in my application. Guide me.
I Do not want this thing
https://developer.android.com/reference/android/view/View.OnTouchListener.html
Thanks .
try this in your activity class,
public class TouchActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
Log.d("Touch", "Touch");
sendBroadcast(new Intent("touch_event_has_occured"));
}
return super.onTouchEvent(event);
}
}
now in your global broadcast receiver you will get the brodcast
public class TouchReveiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals("touch_event_has_occured"))
{
Log.d("Touch", "Touch");
}
}
}
don't forget to register the receiver with the action

Android Detect Pressing On Power Key

My Application needs to know if the screen went off due to timeout or the user clicked the power button.
I decided to check if the power button was pressed.
I read some Q&A here and came up with this :
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button down detected");
return true;
}
return false;
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button up detected");
}
return false;
}
}
I also added this:
<uses-permission android:name="android.permission.PREVENT_POWER_KEY"/>
This doesn't work, it doesn't print the log.
Try to yseing from BroadcastReceiver:
public class MyBroadCastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//DO HERE
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//DO HERE
}
}
}
and your manifest:
<receiver android:name=".MyBroadCastReciever">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
The onKeyDown method, no longer detects the single Power Key click. It does however detect the long press. Here's a very simple trick to capture it, and to differentiate from other buttons and other user's activities that would bring the app to the background.
PwrKeyShortPress = true; // set the default value in your class
....
....
#Override
public void onUserLeaveHint(){
PwrKeyShortPress = false;
super.onUserLeaveHint();
}
#Override
public void onStop() {
if (PwrKeyShortPress) {
// Do something for single Power Key click.
}
PwrKeyShortPress = true;
super.onStop();
}
go this way
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// Power Button pressed
return true;
}
return super.onKeyDown(keyCode, event);
}
EDIT
you can listen to the screen ON/OFF this way
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//do something
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//do something else
}

how to detect long press of volume button in android

I am working on application in which i want to provide facility to user to do specific thing when you long press up or down volume button no matter my app is background or foreground.
I also want to implement this functionality when phone screen off but in stack-overflow posts says you cant do that.
i have used android.media.VOLUME_CHANGED_ACTION broadcast listener for volume button press detection and it work fine no matter your app is background but thing is that i want to detect Long press of these buttons.
how can i include this code into my broadcast so i can detect up or down button press for long time.
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// Do something here...
// Needed to track long presses
Log.e("Main activity", "KEYCODE_VOLUME_UP");
return true;
}
return super.onKeyDown(keyCode, event);
}
This is my broadcast receiver
intentfliter = new IntentFilter("android.media.VOLUME_CHANGED_ACTION");
mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Main activity", "Volume button press");
}
};
getApplicationContext().registerReceiver(mReceiver, intentfliter);
manager.registerMediaButtonEventReceiver(getCallingActivity());
}
package com.example.androidsample;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class VolumeButtonPressedBroadcast extends BroadcastReceiver{
public static boolean sIsReceived; // this is made true and false after each timer clock
public static Timer sTimer=null;
public static int i;
final int MAX_ITERATION=15;
public static boolean sIsAppWorkFinished=true;
#Override
public void onReceive(final Context context, Intent intent)
{
sIsReceived=true; // Make this true whenever isReceived called
if(sTimer==null && sIsAppWorkFinished){
sTimer=new Timer();
sTimer.schedule(new TimerTask() {
#Override
public void run() {
if(sIsReceived){ // if its true it means user is still pressing the button
i++;
}else{ //in this case user must has released the button so we have to reset the timer
cancel();
sTimer.cancel();
sTimer.purge();
sTimer=null;
i=0;
}
if(i>=MAX_ITERATION){ // In this case we had successfully detected the long press event
cancel();
sTimer.cancel();
sTimer.purge();
sTimer=null;
i=0;
//it is called after 3 seconds
}
sIsReceived=false; //Make this false every time a timer iterates
}
}, 0, 200);
}
}
}

I want to end the whole application when user click back button in android

I want to end the whole application when user click back button in android.Currently It again go to previous opened activity.
I also try override onBackPressed() but it doesnt work.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
enter code here
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
return;
}
Try this, start your application from a Activity that will act as your Root.
public class Root extends Activity {
public void onCreate() {
super.onCreate();
handleIntent();
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent();
}
private void handleIntent() {
boolean end = getIntent.getBooleanExtra("End");
if (end) {
finish();
} else {
Intent intent = new Intent(this, MyRealFirstActivity.class); // where this is the class that you want the user to see when they launch your app.
startActivity(intent);
}
}
public void onResume() {
super.onResume();
finish();
}
}
Then inside the activity that you want the back button to end the app, do the following:
public class LastActivity extends Activity {
public void onBackPressed() {
Intent intent = new Intent(this, Root.class);
intent.putExtra("End", true);
intent.addFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
This way all the activities that were started in between you launching the app and then hitting the back button, will all be finished() for you. This essentially will clean the slate of the app from start to finish and then exit.
In this case you need to finish activity, so your current activity will be closed by using finish() method. but you should also write finish() in each and every previous activities, where you call intent(start another activity). Hope it makes clear.
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.finish();
startActivity(intent);
}
Here we have two methods to finish or kill the app on back button pressed.
Using finish() which closes or finishes the current activity on android screen.
for example : you have 2 activities i.e A & B. You ll go from A activity to B activity using intent, now foreground acitivity is B, you want to go back & kill B activity & goto A acitivity use finish() onclick of backbutton. If your on A activity then it closes the app. see below code.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.onKeyDown(keyCode, event);
}
Using android.os.Process.killProcess(android.os.Process.myPid()); which kills the app i.e force close the app & goto the home screen.see below code.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Kills & force closes the app
android.os.Process.killProcess(android.os.Process.myPid());
}
return super.onKeyDown(keyCode, event);
}
Here's the way I did it in my app: ActivityA is the first one to start; it in turn starts ActivityB. In ActivityB I may encounter an error, in which case I Want to return to activityA, or everything may finish correctly, in which case I want to "finish" the app altogether.
In ActivityA:
public class ActivityA extends Activity {
...
private final static int REQUEST_ACT_B = 1;
...
private void startChild() {
startActivityForResult(new Intent(this, ActivityB.class), REQUEST_ACT_B;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_TASK && resultCode == ActivityB.RESULT_OK) {
this.finish();
}
}
}
And then in ActivityB:
public class ActivityB extends Activity {
...
public final static int RESULT_OK = 1;
public final static int RESULT_ERROR = 2;
...
private void finishWithError() {
setResult(RESULT_ERROR);
finish();
}
private void finishSuccessfully() {
setResult(RESULT_OK);
}
}
Essentially, ActivityA starts ActivityB and expects a result back. If it receives back result "OK", then it closes itself and the user is none the wiser: the app has finished. If it received result "error", then ActivityA stays open.

Categories

Resources