获取第三方音乐信息
1、通过notificationListener
<service android:name=".service.MusicNotificationListenerService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
2、 在通知栏中获取音乐信息
public class MusicNotificationListenerService extends NotificationListenerService{
private int musicInfoCount=0;
private String musicTitle,musicSinger;
private String mediaFocusPackageName;
@Override
public void onCreate() {
Log.d("TAG", "onCreate: ");
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.d("TAG", "onNotificationPosted: "+mediaFocusPackageName);
String notificationPkg = sbn.getPackageName();
Log.d("TAG", "onNotificationPosted: ");
if (notificationPkg!=null&¬ificationPkg.equals("需要获取音乐信息的包名")) {
Bundle extras = sbn.getNotification().extras;
musicTitle = extras.getString(Notification.EXTRA_TITLE);
musicSinger = extras.getString(Notification.EXTRA_TEXT);
if (musicTitle==null||"".equals(musicTitle.trim())){
if (sbn.getNotification().bigContentView != null) {
ViewGroup view = (ViewGroup) sbn.getNotification().bigContentView.apply(this, null);
musicInfoCount=0;
getMusicInfo(view);
}
}
Intent intent=new Intent();
intent.setAction("com.media.play");
intent.putExtra("package_name",mediaFocusPackageName);
intent.putExtra("music_title",musicTitle);
intent.putExtra("music_singer",musicSinger);
sendBroadcast(intent);
Log.d("TAG", "onNotificationPosted: name: "+mediaFocusPackageName+
"title: "+musicTitle+
"singer: "+musicSinger);
mediaFocusPackageName=notificationPkg;
}
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
String notificationPkg = sbn.getPackageName();
if (notificationPkg!=null) {
if (mediaFocusPackageName.equals(notificationPkg)){
Intent intent=new Intent();
intent.setAction("com.media.remove");
sendBroadcast(intent);
}
}
}
private void getAllChildView(View view){
ViewGroup viewGroup= (ViewGroup) view;
for (int i=0;i<viewGroup.getChildCount();i++){
View viewchild = viewGroup.getChildAt(i);
if (viewchild instanceof TextView){
Log.d("TAG", "getAllChildView: "+((TextView) viewchild).getText().toString());
}
if (!(viewchild instanceof ViewGroup)){
continue;
}
getAllChildView(viewchild);
}
}
private void getMusicInfo(View view){
ViewGroup viewGroup= (ViewGroup) view;
for (int i=0;i<viewGroup.getChildCount();i++){
View viewchild = viewGroup.getChildAt(i);
if (musicInfoCount>1){
return;
}
if (viewchild instanceof TextView){
Log.d("TAG", "getAllChildView: "+((TextView) viewchild).getText().toString());
if (!"".equals(((TextView) viewchild).getText().toString().trim())){
if (musicInfoCount==0){
musicTitle=((TextView) viewchild).getText().toString();
}else {
musicSinger=((TextView) viewchild).getText().toString();
}
musicInfoCount++;
}
}
if (!(viewchild instanceof ViewGroup)){
continue;
}
getMusicInfo(viewchild);
}
}
}