Обрабатывать мультимедийные кнопки из сервиса в Android 8.0+? - PullRequest
0 голосов
/ 06 марта 2019

Я пытаюсь обработать гарнитуру из службы в Android, чтобы запустить действие для моего приложения с помощью класса MediaSessionCompat, которое отличается от назначения Media Player.

Теперь я написал этот код, которыйработать в Android 7 и ниже, но не с Android 8.0 и выше, и я не знаю почему.

ComponentName componentName = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(componentName);

PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);

MediaSessionCompat mediaSessionCompat = new MediaSessionCompat(getApplicationContext(), getPackageName());
mediaSessionCompat.setCallback(new MediaSessionCompat.Callback()
    {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent)
        {

            KeyEvent keyEvent =
                    (KeyEvent) mediaButtonIntent.getExtras().get(Intent.EXTRA_KEY_EVENT);
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN)
            {
                if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)
                {
                    Log.d(TAG, STRING_EXAMPLE);
                    return true;
                }
            }

            return super.onMediaButtonEvent(mediaButtonEvent);
        }
    });

    mediaSessionCompat.setActive(true);

    mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSessionCompat.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);

Я пытался поместить этот код в OnStart () MainActivity и в onStartCommand моей службы.но ничего не произошло.

Я также пытался оставить это в своем манифесте, но не работает.

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

Я оставляю свой Приемник и Службу, возможно, я где-то обиделся или кто-то может помочья понимаю, почему не работает, к сожалению, Android документ бесполезен для этой вещи.

Приемник:

public class MediaButtonServiceListener extends MediaButtonReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Log.d(TAG, STRING_EXAMPLE);
    }
}

Служба:

public class ExampleService extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText("Service in foregound")
            .setSmallIcon(R.drawable.ic_android)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    return START_NOT_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
}
...