简体   繁体   中英

Broadcast receiver not registering in Android

This is my manifest

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="com.masud.remotecontrol.MyRemoteReceiver" >
        <intent-filter android:priority="1000000000000000" >
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>
</application>

My receiver

static int n_click = 0;

@Override
public void onReceive(final 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();
    switch (event.getKeyCode()) {
    case KeyEvent.KEYCODE_HEADSETHOOK:
        if (action == KeyEvent.ACTION_DOWN) {
            n_click++;
            Handler handler = new Handler();
            Runnable r = new Runnable() {

                @Override
                public void run() {

                    if (n_click == 1) {

                        Log.e("Click==", "Single Click");

                    }

                    if (n_click == 2) {

                        Log.e("Click==", "Double Click");

                    }
                    n_click = 0;
                }
            };
            if (n_click == 1) {

                handler.postDelayed(r, 500);
            }
        }
        break;
    }
    abortBroadcast();
}

I have tried my level best to register my receiver but I have not get any solution in to register. I have tried all the solution found in stackoverflow but no one is working.

All the above code is ok. I just add this code to my MainActivity.

((AudioManager) getSystemService(AUDIO_SERVICE))
            .registerMediaButtonEventReceiver(new ComponentName(this,
                    MyRemoteReceiver.class));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM