2013-04-22 86 views
3
@Override 
public boolean dispatchKeyEvent(KeyEvent event) { 
    int action = event.getAction(); 
    int keyCode = event.getKeyCode(); 
     switch (keyCode) { 
     case KeyEvent.KEYCODE_VOLUME_UP: 
      if (action == KeyEvent.ACTION_UP) { 
       //TODO 
      } 
      return true; 
     case KeyEvent.KEYCODE_VOLUME_DOWN: 
      if (action == KeyEvent.ACTION_DOWN) { 
       //TODO 
      } 
      return true; 
     default: 
      return super.dispatchKeyEvent(event); 
     } 
    } 

此代碼在屏幕打開時工作。但屏幕鎖定時不行。屏幕鎖定時有沒有辦法獲得音量按鍵事件?如何在屏幕鎖定時獲取音量按鍵事件?

+0

解鎖屏幕時要觸發它 – itsrajesh4uguys 2013-04-22 10:03:04

+0

但我需要它,而鎖定 – user2306862 2013-04-22 10:09:07

+0

我的意思解鎖programmatcally .. – itsrajesh4uguys 2013-04-22 10:12:22

回答

3

該事件僅在屏幕打開時觸發..其他明智的根權限是必需的。

做一個BroadcastReceiver擴展分類

public class YourBoardcastReceiver extends BroadcastReceiver { 
       @Override 
       public void onReceive(Context context, Intent intent) { 


Log.e("get something", "i dont know what!!"); 

     String intentAction = intent.getAction(); 
     KeyEvent event = null; 
     if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) { 
      event = (KeyEvent) intent 
        .getParcelableExtra(Intent.EXTRA_KEY_EVENT); 
     } 

     if (event == null) { 
      return; 
     } 

     int keycode = event.getKeyCode(); 
     int action = event.getAction(); 
     long eventtime = event.getEventTime(); 

     if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE 
       || keycode == KeyEvent.KEYCODE_HEADSETHOOK) { 
      if (action == KeyEvent.ACTION_DOWN) { 
       // Start your app here! 

       // ... 
       Log.e("event/////", "Trigerd"); 

       if (isOrderedBroadcast()) { 
        abortBroadcast(); 
       } 
      } 
     } 
    } 
       } 
     } 

而在你的清單:

<receiver android:name="YourBoardcastReceiver"> 
       <intent-filter> 
         <action android:name="android.intent.action.SCREEN_ON" /> 
       </intent-filter> 
</receiver> 

,並這樣稱呼它。

mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
    mRemoteControlResponder = new ComponentName(getPackageName(), 
      YourBoardcastReceiver.class.getName()); 
+0

我不明白:這是OP的答案嗎?頂部的文字有點含糊不清:當屏幕被鎖定時,它是否實際上不調用回調'onReceive'? – 2016-11-20 19:21:55

相關問題