Android - How can i use events of extra physical buttons like pressy - android

I want to use an extra physical button in my app. It is connected to the ear phones plug. I searched the web and didn't find specific answers. Maybe i didnt use the correct search terms?
Are there any tutorials available?
What events are triggered when such a button is pressed?
Is there any difference (in coding) between the original pressy and the cheap china things?
Is it possible to emulate this thing in the adk emulator?
I really want to use this thing in my app, but i dont have a clue how.
I need some help to get started
Any ideas?
Youre answer's helped me to get startet.
Now im am facing new problems, as the toasts i'll try to make to check the responses dont appear. Button press will just play and pause music with the samsung music player on the phone.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.widget.Toast;
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
Toast.makeText(context, "onRecieve triggered", Toast.LENGTH_SHORT).show();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
Toast.makeText(context, "Action lauchched", Toast.LENGTH_SHORT).show();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
if (action == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
// do something
Toast.makeText(context, "Play Pause pressed!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
so it seems that the reciever code isnt reached.
in my activity there are following lines:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ZaehlenActivity.this);
setContentView(R.layout.zaehlen);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);
am i forgettig something? do i have to disable the standard earphone recognition somehow?

I think that earphone buttons are considered as MEDIA_BUTTONS so , you have to create a BroadcastReceiver which listen to android.intent.action.MEDIA_BUTTON and make a test statment to test if the action is an ACTION_DOWN , here's a suite of code it may helps :
This is the BroadcastReceiverwhich you have to declare it in AndroidManifest.xml , and make as Intent-filter : android.intent.action.MEDIA_BUTTON
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
And this is an Activity which listen to the BroadcastReceiverand then make a Toastif one of the buttons was clicked :
public class mainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);
}
}
Hope it helps !

Seeing as Pressy is an external controller (so to speak), you'll need to use a BroadcastReceiver with an intent-filter for: android.intent.action.MEDIA_BUTTON So, for example:
Inside your AndroidManifest:
<receiver android:name="RemoteControlReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
And your new receiver class:
public class RemoteControlReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
// handle media button here
KeyEvent key = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
// handle keydown etc
}
}
}
If you want to check single buttons (maybe on a cabled device, such as headphones, or wireless like Bluetooth), you could also use the onKeyDown and check for KeyEvent.KEYCODE_MEDIA_SOMEKEYIDENTIFIER Like so:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
switch(keyCode){
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
return true;
case KeyEvent.KEYCODE_MEDIA_NEXT:
return true;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
return true;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
return true;
case KeyEvent.KEYCODE_MEDIA_REWIND:
return true;
case KeyEvent.KEYCODE_MEDIA_STOP:
return true;
// etc etc...
}
return false;
}
Hope this at least gets you started. Cheers.

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

How to detect click event of connected Bluetooth peripheral device (Selfie stick)?

I have Selfie stick connected to my phone. I am able to find device ID using below code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Toast.makeText(getApplicationContext(), "ACTION_ACL_CONNECTED" + device, Toast.LENGTH_LONG).show();
}
}
};
My question is how I can detect button press/click event of this connected peripheral device?
Help in form of code snippet/tutorial/comments is highly appreciable.
Thanks!!!
EDIT:
When I press button of Selfie stick Volume + button listen to the event
I found the answer. It was very simple. Just override onKeyDown() method of Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return super.onKeyDown(keyCode, event);
}
Here keyCode is the event name returned.
I have made slight modifications in your code. Please see if its helpful
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter a_filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, a_filter);
IntentFilter b_filter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON);
**b_filter.setPriority(1000);**
this.registerReceiver(mReceiver, b_filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Toast.makeText(getApplicationContext(), "ACTION_ACL_CONNECTED" + device, Toast.LENGTH_LONG).show();
}
if (!Intent.ACTION_CAMERA_BUTTON.equals(action)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
};
Using accessibility service, You can achieve auto-click.
Answer explained here, May be it's helpful to you !

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);
}
}
}

Categories

Resources