标签 Android 下的文章

???

帮别人提出的解决方案(吹B过头),临时突击翻文档学移动开发写的,虽然没有多少行。

得到歌曲名与作者

这里用到了监听器,得到通知栏的网易云的播放控件,读取歌曲名与作者。

来点权限:

<service android:name=".NotificationListener"
        android:label="DemoApp"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
        <meta-data
            android:name="android.service.notification.default_filter_types"
            android:value="1,2">
        </meta-data>
        <meta-data
            android:name="android.service.notification.disabled_filter_types"
            android:value="2">
        </meta-data>
</service>

监听器类:

package com.test.demoapplication;

import android.app.Notification;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;

public class NotificationListener extends NotificationListenerService {
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        //网易云
        if(!sbn.getPackageName().equals("com.netease.cloudmusic")) return;

        //去除一般性通知
        if(!sbn.getNotification().extras.getString(Notification.EXTRA_TEXT,"").equals("")) return;

        //取得通知栏组件
        //另: 网易云支持安卓的MediaBroswerService,这个以后再说
        ViewGroup view = (ViewGroup) sbn.getNotification().bigContentView.apply(this, null);

        String author = (String) ((TextView) (((ViewGroup) view.getChildAt(2))).getChildAt(1)).getText();
        String songName = (String) ((TextView) (((ViewGroup) view.getChildAt(2))).getChildAt(0)).getText();

        Log.i("Debug",songName + "|" + author);

        super.onNotificationPosted(sbn);
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        if(!sbn.getPackageName().equals("com.netease.cloudmusic")) return;
        super.onNotificationRemoved(sbn);
    }
}

控制音乐播放

这个用模拟按键来实现,是通用的,不过要注意开启线控。

//模拟按键要在线程中执行,否则会卡死
class UPressKey extends Thread {
    private int keyCode;
    public UPressKey(int keyCode) {
        this.keyCode = keyCode;
    }

    @Override
    public void run() {
        Instrumentation mInst = new Instrumentation();
        mInst.sendKeyDownUpSync(this.keyCode);
    }
}


//以下为控制按键
new UPressKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS).start();
new UPressKey(KeyEvent.KEYCODE_VOLUME_UP).start();
new UPressKey(KeyEvent.KEYCODE_MEDIA_PLAY).start();
new UPressKey(KeyEvent.KEYCODE_VOLUME_DOWN).start();
new UPressKey(KeyEvent.KEYCODE_MEDIA_NEXT).start();
new UPressKey(KeyEvent.KEYCODE_MEDIA_PAUSE).start();

实现

24 185911.jpg