1234567
1234567

Reputation: 2485

How to detect android headset button click on 4.0 and higher

I am trying to detect Headset button click referring to this

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

This is the code I haave tried

public class MainActivity extends Activity {


    private IntentFilter mIntentFilter;

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

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mIntentFilter.setPriority(2147483647);



        registerReceiver(mReceiver, mIntentFilter);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @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) {
                Toast.makeText(MainActivity.this,"Your Message", Toast.LENGTH_LONG).show();

            }
            abortBroadcast();

        }
    };

    @Override
    protected void onPause() {
        unregisterReceiver(mReceiver);
        super.onPause();
    }

All I am trying to do is get a toast message for the button click received , but it is just not getting detected What exactly should be done to detect the button click .

I am testing on a real android device with Android 4.2.1

Upvotes: 1

Views: 1150

Answers (1)

Neirid
Neirid

Reputation: 363

Have you registered your broadcast receiver in AndroidManifest.xml?

<receiver android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

Upvotes: 2

Related Questions