I want to call a function when MEDIA_BUTTON
is clicked. But in extended BroadcastReceiver
class Constructor
is called but onReceive
function is not called.
I have test this over a BluetoothDevice as it has no affect. by this
Content in Manifest.xml File
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NotificationManager">
<meta-data
android:name="com.google.android.actions"
android:resource="@xml/actions" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NotificationService"
android:enabled="true"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter android:priority="1000000000">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
How I registered BroadcastReceiver
in MainActivity.java
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);
Content in MediaButtonIntentReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class MediaButtonIntentReceiver extends BroadcastReceiver{
private static final String TAG = "MediaButtonReceive";
MediaButtonIntentReceiver(){
super();
Log.e(TAG, "Constructor Called"); //Also tried without Constructor.
}
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "In onReceive"); // It won't even print this.
String intentAction = intent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int keycode = event.getKeyCode();
int action = event.getAction();
if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
if (action == KeyEvent.ACTION_DOWN) {
Log.e(TAG, "Button Pressed"); //Call function here.
Toast.makeText(context, "Button pressed !!", Toast.LENGTH_SHORT).show();
if (isOrderedBroadcast()) {
abortBroadcast();
}
}
}
}
}
}
I have referred at least 8 Stack's answers but unable to solve this issue.