我一直在努力实现这一目标。
我发现了这一点,但他们似乎并没有帮助我:

http://android.amberfog.com/?p=415

Registering a headset button click with BroadcastReceiver in Android

https://issuetracker.google.com/issues/36910848

无论我按下头上的按钮如何尝试,手机都将显示音量控制,而不是被我的应用程序抓紧并做一些事情。这是一些代码:

public class MediaButtonIntentReceiver extends BroadcastReceiver {

public MediaButtonIntentReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent intent) {
    Log.i("test1'", "test2");
    String intentAction = intent.getAction();
    if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
        return;
    }
    KeyEvent event = (KeyEvent) intent
            .getParcelableExtra(Intent.EXTRA_KEY_EVENT);
    if (event == null) {
        Log.i("test3'", "test4");
        return;
    }
    int action = event.getAction();
    if (action == KeyEvent.ACTION_DOWN) {
        // do something
        Log.i("test5'", "test6");
    }
    abortBroadcast();
}
}

public class MainActivity extends Activity {

private static final String TAG = "BTAudioActivity";

private MediaPlayer mPlayer = null;
private AudioManager amanager = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    amanager = (AudioManager) getSystemService(AUDIO_SERVICE);
    amanager.setBluetoothScoOn(true);
    amanager.startBluetoothSco();
    amanager.setMode(2);

    mPlayer = new MediaPlayer();

    try {
        mPlayer.setDataSource(new FileInputStream("/sdcard/sample.wav")
                .getFD());
        mPlayer.prepare();
        mPlayer.setVolume(8,8);

        mPlayer.start();

    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
    @Override
protected void onResume() {
    // TODO Auto-generated method stub
MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(1000);
registerReceiver(mMediaButtonReceiver, mediaFilter);
    super.onResume();
}

@Override
public void onDestroy() {
    mPlayer.stop();
    amanager.setMode(2);
    amanager.setBluetoothScoOn(false);
    super.onDestroy();
}
}

最佳答案

尝试在onCreate中注册...
并使用this添加电源管理器wake_lock

10-01 08:20