から派生しActivity
た とを含む単純な Android アプリがあります。と を使用して、メイン アクティビティからオーディオを再生するようにセットアップすることに成功しました。Bluetooth ヘッドフォンからのオーディオを再生および一時停止することもできます。すべて良い。Service
MediaBrowserServiceCompat
MediaBrowserCompat
MediaControllerCompat
私の課題はNotificationCompat.MediaStyle
、ロック画面と通知トレイに表示される通知に関するものです。通知は正常に表示されます。ただし、 と を使用してボタンを追加するaddAction()
とMediaButtonReceiver.buildMediaButtonPendingIntent
、何もしません。代わりに、メイン アクティビティを起動するだけのダミーの PendingIntent を追加すると、問題なく動作します。
通知を生成するためのコードを次に示します (申し訳ありませんが、これは Xamarin で実行されている C# であるため、大文字と小文字の区別と名前は、予想とは少し異なります)。これは私のサービスクラスの中にあります。
var builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetVisibility(NotificationCompat.VisibilityPublic)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Title")
.SetContentText("Content")
.SetSubText("Subtext")
.SetLargeIcon(icon)
.SetColor(Android.Graphics.Color.DarkOrange)
.SetContentIntent(intent)
.SetDeleteIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(this, PlaybackStateCompat.ActionStop))
.AddAction(new NotificationCompat.Action(
Resource.Drawable.ic_pause, "Pause",
MediaButtonReceiver.BuildMediaButtonPendingIntent(this, PlaybackStateCompat.ActionPause)))
.SetStyle(new Android.Support.V4.Media.App.NotificationCompat.MediaStyle()
.SetShowActionsInCompactView(0)
.SetMediaSession(this.mediaSession.SessionToken)
.SetShowCancelButton(true)
.SetCancelButtonIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(this, PlaybackStateCompat.ActionStop))
);
this.StartForeground(NOTIFICATION_ID, builder.Build());
これを解決するためにこれまで見てきたことは次のとおりです。
- 再生を開始するときに使用します
MediaSession.setActive(true)
- 再生を開始および停止するたびに、適切なアクションを
PlaybackStateCompat
- セッショントークンが正しく設定されています。
- Android 5.0 以降をターゲットにしてクラスを使用しているため、マニフェストにとして何も設定していません。
MediaButtonReceiver
android.intent.action.MEDIA_BUTTON
*Compat
Bluetooth ヘッドフォン ボタンが機能するため、メディア ボタン イベントがアプリに適切にルーティングされていることはわかっています。私は自分の車で試してみましたが、そこでも機能します。機能しないのは、通知のボタンだけです。の適切なメソッドへの呼び出しを生成することを期待していますMediaSessionCompat.Callback
。これは間違っていますか?ここで何が間違っていますか?
任意のポインタに感謝します。
更新:
私はそれを働かせました。<application>
マニフェストのノード内に次を追加する必要がありました。
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
...そして、実装する Service のノード内の以下MediaBrowserServiceCompat
:
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter>
Bluetooth ヘッドフォンとカー インフォテインメント システムからボタンを押すと、アプリに問題なくルーティングされたので、なぜこれが必要なのか、まだ少し混乱しています。さらに重要なことに、Googleは次のように述べています。
MediaBrowserServiceCompat
アプリに が既にある場合はMediaButtonReceiver
、受信したキー イベントをMediaBrowserServiceCompat
デフォルトで に配信します。でそれらを処理できますMediaSessionCompat.Callback
。
彼らはこれを「Service Handling ACTION_MEDIA_BUTTON」オプションの代替として提供したので、マニフェストでこれ以上何もする必要がないことを意味すると考えました。誰かがここで私を啓発できるなら、私はそれを感謝します.
しかし、それだけの価値はありますが、これは私にとってはうまくいきました。