1.利用MediaSession发送信息到蓝牙音箱,如:播放音乐时接收的歌曲信息,但是每一首歌连续播放时,再次发送的重复信息会被丢弃。则利用MediaSession发现信息时,要保证信息的不重复性。
2.
public MediaSessionCompat mMediaSession;
private Handler sHandler;
public void initMediaSession(){
mMediaSession = new MediaSessionCompat(this, "MusicService");
sHandler = new Handler(Looper.getMainLooper());
mMediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(Intent intent) {
android.support.v4.media.session.MediaButtonReceiver mMediaButtonReceiver = new android.support.v4.media.session.MediaButtonReceiver();
mMediaButtonReceiver.onReceive(SettingActivity.this, intent);
return true;
}
}, sHandler);
mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
Context context = getApplicationContext();
Intent intent = new Intent(context, HomeActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 99 /*request code*/,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
mMediaSession.setSessionActivity(pi);
if (!mMediaSession.isActive()) {
mMediaSession.setActive(true);
}
}
3. 注册的Receiver
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
4.
if(mMediaSession==null){
initMediaSession();
}
MediaMetadataCompat.Builder md = new MediaMetadataCompat.Builder();
md.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "#Wifi#" + UUID.randomUUID().toString());
wifiName="NETGEAR84";wifiPwd="aaaaaaaa@";
md.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, wifiName);
md.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, wifiPwd);
md.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 100);
mMediaSession.setMetadata(md.build());
mMediaSession.setCallback(null);
mMediaSession.setActive(false);
mMediaSession.release();
mMediaSession=null;
5.