how to detect long press of volume button in android

前端 未结 1 1512
刺人心
刺人心 2021-01-03 17:29

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 f

1条回答
  •  没有蜡笔的小新
    2021-01-03 17:56

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

    0 讨论(0)
提交回复
热议问题