Android中的耳机按钮

时间:2013-09-17 15:19:26

标签: android headset

我将我的意图的priority设置为100000但是当我按下耳机按钮时,我的应用程序仍被忽略。相反,只需触发手机中的Built-in音乐播放器即可。我需要做些什么来完成这项工作?

这是我的代码

public class MainActivity extends Activity {

    private Headset headset = new Headset();
    public TextView txt;

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

        txt = (TextView) findViewById(R.id.TEXT);

        Headset headset = new Headset();
        IntentFilter mFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        mFilter.setPriority(1);
        registerReceiver(headset, mFilter);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        unregisterReceiver(headset);
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class Headset extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            String intAction = arg1.getAction();

            if (!Intent.ACTION_MEDIA_BUTTON.equals(intAction)){
                return;
            }

            KeyEvent event = (KeyEvent)arg1.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

            if(event==null){
                return;
            }

            int action = event.getAction();
            if (action==KeyEvent.ACTION_DOWN){
                txt.setText("you clicked me!!!");
            }

            abortBroadcast();
        }
    }
}

0 个答案:

没有答案