我正在处理应用程序,我想为用户提供设施,当你长按或按下音量按钮时,无论我的应用程序是背景还是前景,都要做特定的事情。
我还希望在手机屏幕关闭时实现此功能,但在堆栈溢出帖子中说你不能这样做。
我已经使用android.media.VOLUME_CHANGED_ACTION
广播监听器进行音量按钮按下检测,无论您的应用程序是背景,它都能正常工作,但事实是我想要检测长按这些按钮。
如何将此代码包含在我的广播中,以便我可以长时间按下向上或向下按钮。
@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);
}
这是我的广播接收器
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());
}
答案 0 :(得分:3)
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);
}
}
}