Autojs 使用总结

用 root 打开无障碍模式

function enable(packageName) {
    shell(`settings put secure enabled_accessibility_services ${packageName}/com.stardust.autojs.core.accessibility.AccessibilityService`, true)
}

用 root 添加省电模式白名单

function addBatteryWhiteList(packageName) {
    shell(`dumpsys deviceidle whitelist +${packageName}`,true)
}

保活

  • 添加省电模式白名单
  • 发送一条保活通知

KeepAliveService = {
    /** 开启 */
    start: function (idStr, nameStr) {
        try {
            idStr = idStr || "";
            let channel_id = idStr + ".foreground";
            let channel_name = nameStr + " 前台服务通知";

            let content_title = nameStr + " 正在运行中";
            let content_text = "请勿手动移除该通知";

            let ticker = nameStr + "已启动";

            let manager = context.getSystemService(android.app.Service.NOTIFICATION_SERVICE);
            let notification;
            let icon = context.getResources().getIdentifier("ic_android_eat_js", "drawable", context.getPackageName());
            if (device.sdkInt >= 26) {
                let channel = new android.app.NotificationChannel(channel_id, channel_name, android.app.NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true);
                channel.setLightColor(0xff0000);
                channel.setShowBadge(false);
                manager.createNotificationChannel(channel);
                notification = new android.app.Notification.Builder(context, channel_id).setContentTitle(content_title).setContentText(content_text).setWhen(new Date().getTime()).setSmallIcon(icon).setTicker(ticker).setOngoing(true).build();
            } else {
                notification = new android.app.Notification.Builder(context).setContentTitle(content_title).setContentText(content_text).setWhen(new Date().getTime()).setSmallIcon(icon).setTicker(ticker).build();
            }
            manager.notify(1, notification);
        } catch (error) {
            console.warn("前台保活服务启动失败:" + error);
            console.warn("保活服务启动失败,不影响辅助的正常运行,继续挂机即可.");
        }
    },
    /** 停止 */
    stop: function () {
        let manager = context.getSystemService(android.app.Service.NOTIFICATION_SERVICE);
        manager.cancelAll();
    },
};

// KeepAliveService.start('auto', 'auto');
  • 打开console,让autojs的脚本可以前台运行
  • 自定义安卓启动命令,每10分钟判断进程,如果进程不在,就重新打开app
packageName="com.example.auto"
function run(packageName){
  settings put global package_verifier_user_consent -1
  pm clear $packageName
  cmd activity add-root-permission $packageName
  pm reset-permissions
  pm grant $packageName android.permission.READ_EXTERNAL_STORAGE
  pm grant $packageName android.permission.WRITE_EXTERNAL_STORAGE
  dumpsys deviceidle whitelist +$packageName

  monkey -p $packageName 1

  echo 'Started autojs application'
}
run
while :
do
    pidof $packageName || run($packageName)
    sleep 600
done