Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support player control through headset hook button #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,53 @@
import android.content.Intent;
import android.view.KeyEvent;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class MediaButtonsReceiver extends BroadcastReceiver {
private static final String TAG = "MediaButtonsReceiver";
public static final int NO_KEY = -1;
private static int keyCode = NO_KEY;
private static long smartKeyPressMaxDelayMs = 500;
protected boolean ordered = true;
protected static final Semaphore smartButtonSem = new Semaphore(0);

protected static Thread smartKeyThread = new Thread(new Runnable() {
public void run() {
Log.i(TAG, "Started smart button thread");
try {
while (true) {
smartButtonSem.acquire();
int pressCount = 1;
Log.i(TAG, "First smart button press, waiting next presses...");
while (smartButtonSem.tryAcquire(smartKeyPressMaxDelayMs, TimeUnit.MILLISECONDS)) {
pressCount++;
Log.i(TAG, "Smart button press #" + pressCount + ", waiting next presses...");
}
Log.i(TAG, "Total smart button key presses: " + pressCount);
switch (pressCount) {
case 1: //play/pause
keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
break;
case 2: // next
keyCode = KeyEvent.KEYCODE_MEDIA_NEXT;
break;
default: // previous
keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS;
break;
}
}
} catch (InterruptedException ex) {
Log.e(TAG, ex.getMessage());
}
}
});

public MediaButtonsReceiver() {
if (!smartKeyThread.isAlive()) {
smartKeyThread.start();
}
}

@Override
public void onReceive(final Context context, final Intent intent) {
Expand All @@ -36,6 +77,10 @@ public void onReceive(final Context context, final Intent intent) {
Log.i(TAG, "Key code " + code);
keyCode = code;
break;
case KeyEvent.KEYCODE_HEADSETHOOK:
Log.i(TAG, "Smart key pressed");
smartButtonSem.release();
break;
default:
Log.i(TAG, "Unhandled key code " + code);
}
Expand Down