Android - 检查耳机按钮点击

时间:2012-04-12 13:58:39

标签: android implementation headset

如何点击我的耳机中的播放/暂停按钮? 之后,我可以实现一些方法,可以改变我自己的行动(关闭等)的典型动作(播放/暂停)吗?

3 个答案:

答案 0 :(得分:4)

现在我正在使用下面的代码耳机按钮点击事件,它为我工作。试试这段代码

enter code here
//Receiver

public class MediaButtonEventReceiver extends BroadcastReceiver {

    private static final String TAG = "MediaButtonIntentReceiv";
    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
            Log.e(TAG, "onReceive: " );
            Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
        }


        abortBroadcast();
    }
}

//Write this code in onCreateview in your activity 

       IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
        filter.setPriority(1000); //this line sets receiver priority
        registerReceiver(r, filter);

//  manifest.xml 
 <receiver android:name=".MediaButtonIntentReceiver">
            <intent-filter >
                <action android:name="android.intent.action.MEDIA_BUTTON"/>
            </intent-filter>
        </receiver>

答案 1 :(得分:3)

如果您尝试通过前台活动收听此消息,请使用onKeyDown()并注意KEYCODE_MEDIA_PLAY_PAUSE

如果您尝试从后台收听此活动(例如,播放音乐的服务),请使用BroadcastReceiver ACTION_MEDIA_BUTTON

答案 2 :(得分:0)

您可以使用ACTION_MEDIA_BUTTON意图 阅读以上链接 希望这个帮助