隐藏

超全的auto.js基础操作,目前是autoX.js的控制方式

发布:2023/10/19 23:17:52作者:管理员 来源:本站 浏览次数:678

02_auto.js基础操作1/4


   安卓手势点击左上角拉出通知栏三指捏合三指下滑双指捏合心形手势解压缩示例一示例二本地存储保存数组和复杂对象保存整数登简单数据随手记传感器打印常用传感器信息显示常用传感器信息调用JavaAPI定时器定时执行循环执行对话框菜单单选框多选框简单计算器模拟更新下载对话框确认框输入框UI模式下使用对话框多媒体免root屏幕录制音乐播放器多线程变量可见性实验多线程按键监听多线程简单示例线程启动与关闭原子变量


安卓手势

点击左上角


"auto";


setScreenMetrics(1080, 1920);   // 屏幕分辨率1080*1920


click(100, 150);


拉出通知栏


"auto";


//表示从位置(500, 10)滑动到位置(500, 1000), 持续两秒

swipe(500, 10, 500, 1000, 2000);


三指捏合


"auto";

setScreenMetrics(1080, 1920);

//如果你使用的是MIUI,此脚本运行后会出现桌面多屏幕编辑

home();

sleep(1500);

gestures([350, [800, 300], [500, 1000]],

        [350, [300, 1500], [500, 1000]],

        [350, [300, 300], [500, 1000]]);


三指下滑


"auto";

/**

* 同时模拟三个手势:

* 从(300, 400)到(300, 1400)

* 从(600, 400)到(600, 1400)

* 从(900, 400)到(900, 1400)

* 每一个的时长都为350毫秒

*/

gestures([350, [300, 400], [300, 1400]],

        [350, [600, 400], [600, 1400]],

        [350, [900, 400], [900, 1400]]

);


双指捏合


"auto";


setScreenMetrics(1080, 1920);


//如果你使用的是MIUI,此脚本运行后会出现桌面编辑

home();

sleep(1500);

gestures([500, [800, 300], [500, 1000]],

        [500, [300, 1500], [500, 1000]]);


心形手势


"auto";


toast("开启开发者选项-指针位置或者在画画软件才能查看效果");


setScreenMetrics(1080, 1920);


var points = [10000];

var interval = 0.1;

var x0 = 600;

var y0 = 1000;

var a = 120;


for(var t = 0; t < 2 * Math.PI; t += interval){

   var x = x0 + a * (2 * Math.cos(t) - Math.cos(2 * t));

   var y = y0 + a * (2 * Math.sin(t) - Math.sin(2 * t));

   points.push([parseInt(x), parseInt(y)]);

}


gesture.apply(null, points);


解压缩

示例一


//压缩文件路径(必须是完整路径)

var filePath = "/sdcard/脚本.7z";

//目录路径(必须是完整路径)

var dirPath = "/sdcard/脚本";

//压缩类型

//支持的压缩类型包括:zip 7z bz2 bzip2 tbz2 tbz gz gzip tgz tar wim swm xz txz。

var type = "7z";

//压缩密码

var password = "password"


//7z加密压缩(若文件已存在则跳过)

//zips.A(type, filePath, dirPath, password)


//压缩

switch (zips.A(type, filePath, dirPath)) {

   case 0:

       toastLog("压缩成功!文件已保存为: " + filePath)

       break;

   case 1:

       toastLog("压缩结束,存在非致命错误(例如某些文件正在被使用,没有被压缩)")

       break;

   case 2:

       toastLog("致命错误")

       break;

   case 7:

       toastLog("命令行错误")

       break;

   case 8:

       toastLog("没有足够内存")

       break;

   case 255:

       toastLog("用户中止操作")

       break;

   default: toastLog("未知错误")

}


示例二


// 准备工作,创建文件夹与文件,以便后续用于压缩

// 创建两个文件夹与三个文件

$files.create("/sdcard/脚本/zip_test/");

$files.create("/sdcard/脚本/zip_out/");

$files.write("/sdcard/脚本/zip_test/1.txt", "Hello, World");

$files.write("/sdcard/脚本/zip_test/2.txt", "GoodBye, World");

$files.write("/sdcard/脚本/zip_test/3.txt", "Autox.js");


// 1. 压缩文件夹

// 要压缩的文件夹路径

let dir = '/sdcard/脚本/zip_test/';

// 压缩后的文件路径

let zipFile = '/sdcard/脚本/zip_out/未加密.zip';

$files.remove(zipFile);

$zip.zipDir(dir, zipFile);


// 2.加密压缩文件夹

let encryptedZipFile = '/sdcard/脚本/zip_out/加密.zip';

$files.remove(encryptedZipFile);

$zip.zipDir(dir, encryptedZipFile, {

   password: 'Autox.js'

});


// 3. 压缩单个文件

let zipSingleFie = '/sdcard/脚本/zip_out/单文件.zip'

$files.remove(zipSingleFie);

$zip.zipFile('/sdcard/脚本/zip_test/1.txt', zipSingleFie);


// 4. 压缩多个文件

let zipMultiFile = '/sdcard/脚本/zip_out/多文件.zip';

$files.remove(zipMultiFile);

let fileList = ['/sdcard/脚本/zip_test/1.txt', '/sdcard/脚本/zip_test/2.txt']

$zip.zipFiles(fileList, zipMultiFile);


// 5. 解压文件

$zip.unzip('/sdcard/脚本/zip_out/未加密.zip', '/sdcard/脚本/zip_out/未加密/');


// 6. 解压加密的zip

$zip.unzip('/sdcard/脚本/zip_out/加密.zip', '/sdcard/脚本/zip_out/加密/', {

   password: 'Autox.js'

});


// 7. 从压缩包删除文件

let z = $zip.open('/sdcard/脚本/zip_out/多文件.zip');

z.removeFile('1.txt');


// 8. 为压缩包增加文件

z.addFile('/sdcard/脚本/zip_test/3.txt');


本地存储

保存数组和复杂对象


var storage = storages.create("Auto.js例子:复杂数据");

var arr = [1, 4, 2, 5];

var obj = {

   name: "Auto.js",

   url: "www.autojs.org"

};

//保存

storage.put("arr", arr);

storage.put("obj", obj);


console.show();

//取出

log("arr = ", storage.get("arr"));

log("obj = ", storage.get("obj"));


保存整数登简单数据


var storage = storages.create("Auto.js例子:简单数据");

var a = 1234;

var b = true;

var str = "hello";

//保存

storage.put("a", a);

storage.put("b", b);

storage.put("str", str);


console.show();

//取出

log("a = " + storage.get("a"));

log("b = " + storage.get("b"));

log("str = " + storage.get("str"));


随手记


"ui";

ui.layout(

   <vertical padding="16">

       <horizontal>

           <text textColor="black" textSize="18sp" layout_weight="1">随手记</text>

           <button id="save" text="保存" w="auto" style="Widget.AppCompat.Button.Borderless.Colored"/>

       </horizontal>

       <input id="content" h="*" gravity="top"/>

   </vertical>

);

var storage = storages.create("Auto.js例子:随手记");

var content = storage.get("content");

if(content != null){

   ui.content.setText(content);

}

ui.save.click(()=>{

   storage.put("content", ui.content.text());

});


传感器

打印常用传感器信息


//忽略不支持的传感器,即使有传感器不支持也不抛出异常

sensors.ignoresUnsupportedSensor = true;


sensors.on("unsupported_sensor", function(sensorName, sensorType){

   log("不支持的传感器: %s 类型: %d", sensorName, sensorType);

});


//加速度传感器

sensors.register("accelerometer").on("change", (event, ax, ay, az)=>{

   log("x方向加速度: %d\ny方向加速度: %d\nz方向加速度: %d", ax, ay, az);

});

//方向传感器

sensors.register("orientation").on("change", (event, dx, dy, dz)=>{

   log("绕x轴转过角度: %d\n绕y轴转过角度: %d\n绕z轴转过角度: %d", dx, dy, dz);

});

//陀螺仪传感器

sensors.register("gyroscope").on("change", (event, wx, wy, wz)=>{

   log("绕x轴角速度: %d\n绕y轴角速度: %d\n绕z轴角速度: %d", wx, wy, wz);

});

//磁场传感器

sensors.register("magnetic_field").on("change", (event, bx, by, bz)=>{

   log("x方向磁场强度: %d\ny方向磁场强度: %d\nz方向磁场强度: %d", bx, by, bz);

});

//重力传感器

sensors.register("magnetic_field").on("change", (event, gx, gy, gz)=>{

   log("x方向重力: %d\ny方向重力: %d\nz方向重力: %d", gx, gy, gz);

});

//线性加速度传感器

sensors.register("linear_acceleration").on("change", (event, ax, ay, az)=>{

   log("x方向线性加速度: %d\ny方向线性加速度: %d\nz方向线性加速度: %d", ax, ay, az);

});

//温度传感器

sensors.register("ambient_temperature").on("change", (event, t)=>{

   log("当前温度: %d", t);

});

//光线传感器

sensors.register("light").on("change", (event, l)=>{

   log("当前光的强度: %d", l);

});

//压力传感器

sensors.register("pressure").on("change", (event, p)=>{

   log("当前压力: %d", p);

});

//距离传感器

sensors.register("proximity").on("change", (event, d)=>{

   log("当前距离: %d", d);

});

//湿度传感器

sensors.register("relative_humidity").on("change", (event, rh)=>{

   log("当前相对湿度: %d", rh);

});


//30秒后退出程序

setTimeout(exit, 30 * 1000);


显示常用传感器信息


"ui";


ui.layout(

   <scroll>

       <vertical>

           <text id="accelerometer" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="orientation" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="gyroscope" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="magnetic_field" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="gravity" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="linear_acceleration" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="ambient_temperature" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="light" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="pressure" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="proximity" margin="12dp" textSize="16sp" textColor="#000000"/>

           <text id="relative_humidity" margin="12dp" textSize="16sp" textColor="#000000"/>

       </vertical>

   </scroll>

);


//忽略不支持的传感器,即使有传感器不支持也不抛出异常

sensors.ignoresUnsupportedSensor = true;


sensors.on("unsupported_sensor", function(sensorName, sensorType){

   log(util.format("不支持的传感器: %s 类型: %d", sensorName, sensorType));

});


//加速度传感器

sensors.register("accelerometer", sensors.delay.ui).on("change", (event, ax, ay, az)=>{

   ui.accelerometer.setText(util.format("x方向加速度: %d\ny方向加速度: %d\nz方向加速度: %d", ax, ay, az));

});

//方向传感器

sensors.register("orientation", sensors.delay.ui).on("change", (event, dx, dy, dz)=>{

   ui.orientation.setText(util.format("绕x轴转过角度: %d\n绕y轴转过角度: %d\n绕z轴转过角度: %d", dx, dy, dz));

});

//陀螺仪传感器

sensors.register("gyroscope", sensors.delay.ui).on("change", (event, wx, wy, wz)=>{

   ui.gyroscope.setText(util.format("绕x轴角速度: %d\n绕y轴角速度: %d\n绕z轴角速度: %d", wx, wy, wz));

});

//磁场传感器

sensors.register("magnetic_field", sensors.delay.ui).on("change", (event, bx, by, bz)=>{

   ui.magnetic_field.setText(util.format("x方向磁场强度: %d\ny方向磁场强度: %d\nz方向磁场强度: %d", bx, by, bz));

});

//重力传感器

sensors.register("gravity", sensors.delay.ui).on("change", (event, gx, gy, gz)=>{

   ui.gravity.setText(util.format("x方向重力: %d\ny方向重力: %d\nz方向重力: %d", gx, gy, gz));

});

//线性加速度传感器

sensors.register("linear_acceleration", sensors.delay.ui).on("change", (event, ax, ay, az)=>{

   ui.linear_acceleration.setText(util.format("x方向线性加速度: %d\ny方向线性加速度: %d\nz方向线性加速度: %d", ax, ay, az));

});

//温度传感器

sensors.register("ambient_temperature", sensors.delay.ui).on("change", (event, t)=>{

   ui.ambient_temperature.setText(util.format("当前温度: %d", t));

});

//光线传感器

sensors.register("light", sensors.delay.ui).on("change", (event, l)=>{

   ui.light.setText(util.format("当前光的强度: %d", l));

});

//压力传感器

sensors.register("pressure", sensors.delay.ui).on("change", (event, p)=>{

   ui.pressure.setText(util.format("当前压力: %d", p));

});

//距离传感器

sensors.register("proximity", sensors.delay.ui).on("change", (event, d)=>{

   ui.proximity.setText(util.format("当前距离: %d", d));

});

//湿度传感器

sensors.register("relative_humidity", sensors.delay.ui).on("change", (event, rh)=>{

   ui.relative_humidity.setText(util.format("当前相对湿度: %d", rh));

});


//30秒后退出程序

setTimeout(exit, 30 * 1000);


调用JavaAPI


/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-

*

* This Source Code Form is subject to the terms of the Mozilla Public

* License, v. 2.0. If a copy of the MPL was not distributed with this

* file, You can obtain one at http://mozilla.org/MPL/2.0/. */


/**

* liveConnect.js: a simple demonstration of javascript-to-Java connectivity

*/


// Create a new StringBuffer. Note that the class name must be fully qualified

// by its package. Packages other than "java" must start with "Packages", i.e.,

// "Packages.javax.servlet...".

var sb = new java.lang.StringBuffer();


// Now add some stuff to the buffer.

sb.append("hi, mom");

sb.append(3); // this will add "3.0" to the buffer since all JS numbers

 // are doubles by default

sb.append(true);


// Now print it out. (The toString() method of sb is automatically called

// to convert the buffer to a string.)

// Should print "hi, mom3.0true".

print(sb);

openConsole();


定时器

定时执行


toast("静等20秒,你会看到想看的...");


var i = 0;


setTimeout(function(){

   app.openUrl("http://music.163.com/#/song?id=109628&autoplay=true&market=baiduhd");

   exit();

}, 20 * 1000);


setInterval(function(){

   i++;

   toast(i * 5 + "秒");

}, 5000);


循环执行


var i = 0;


setInterval(function(){

   i++;

   toast(i * 4 + "秒");

   if(i == 5){

       exit();

   }

}, 4000);


对话框

菜单


while(true){

   var i = dialogs.select("哲学的基本问题是", "社会和自然的关系问题", "思维与存在的关系问题", "政治和经济的关系问题", "实践和理论的关系问题");

   if(i == -1){

       toast("猜一下呗");

       continue;

   }

   if(i == 1){

       toast("答对辣");

       break;

   }else{

       toast("答错辣")

   }

}


单选框


var sex = dialogs.singleChoice("请选择性别", ["男", "女", "基佬", "女装", "其他"], 2);

toast("选择了第" + (sex + 1) + "个选项");


多选框


var i = dialogs.multiChoice("下列作品出自李贽的是", ["《焚书》", "《西湖寻梦》", "《高太史全集》", "《续焚烧书》", "《藏书》"]);

toast("选择了: " + i);

if(i.length == 2 && i.toString() == [0, 4].toString()){

   toast("答对辣");

}else{

   toast("答错辣");

}


简单计算器


var num1 = dialogs.input("请输入第一个数字");

var op = dialogs.singleChoice("请选择运算", ["加", "减", "乘", "除", "幂"]);

var num2 = dialogs.input("请输入第二个数字");

var result = 0;

switch(op){

case 0:

   result = num1 + num2;

   break;

case 1:

   result = num1 - num2;

   break;

case 2:

   result = num1 * num2;

   break;

case 3:

   result = num1 / num2;

   break;

case 4:

   result = Math.pow(num1, num2);

   break;

}

alert("运算结果", result);


模拟更新下载对话框


var releaseNotes = "版本 v7.7.7\n"

   + "更新日志:\n"

   + "* 新增 若干Bug\n";

dialogs.build({

   title: "发现新版本",

   content: releaseNotes,

   positive: "立即下载",

   negative: "取消",

   neutral: "到浏览器下载"

})

   .on("positive", download)

   .on("neutral", () => {

       app.openUrl("https://www.autojs.org");

   })

   .show();


var downloadDialog = null;

var downloadId = -1;


function download(){

   downloadDialog = dialogs.build({

       title: "下载中...",

       positive: "暂停",

       negative: "取消",

       progress: {

           max: 100,

           showMinMax: true

       },

       autoDismiss: false

   })

       .on("positive", ()=>{

           if(downloadDialog.getActionButton("positive") == "暂停"){

               stopDownload();

               downloadDialog.setActionButton("positive", "继续");

           }else{

               startDownload();

               downloadDialog.setActionButton("positive", "暂停");

           }

       })

       .on("negative", ()=>{

           stopDownload();

           downloadDialog.dismiss();

           downloadDialog = null;

       })

       .show();

   startDownload();

}


function startDownload(){

   downloadId = setInterval(()=>{

       var p = downloadDialog.getProgress();

       if(p >= 100){

           stopDownload();

           downloadDialog.dismiss();

           downloadDialog = null;

           toast("下载完成");

       }else{

           downloadDialog.setProgress(p + 1);

       }

   }, 100);

}


function stopDownload(){

   clearInterval(downloadId);

}


确认框


var handsome = confirm("你帅吗?");

if(handsome){

   toast("真不要脸!");

   toast("真不要脸!");

   toast("真不要脸!");

   alert("真不要脸!");

}else{

   toast("嗯");

}


输入框


var name = rawInput("请输入名字");

alert("(•́へ•́╬)", "你好~ " + name);

var expr = dialogs.input("请输入简单的算式", "1+1");

alert("计算结果为 " + expr);


UI模式下使用对话框


"ui";


ui.layout(

   <vertical>

       <button id="callback" align="center">回调形式</button>

       <button id="promise" align="center">Promise形式</button>

       <button id="calc" align="center">简单计算器</button>

   </vertical>

);


ui.callback.click(()=>{

   dialogs.confirm("要弹出输入框吗?", "", function(b){

       if(b){

           dialogs.rawInput("输入", "", function(str){

               alert("您输入的是:" + str);

           });

       }else{

           ui.finish();

       }

   });

});


ui.promise.click(()=>{

   dialogs.confirm("要弹出输入框吗")

       .then(function(b){

           if(b){

              return dialogs.rawInput("输入");

           }else{

               ui.finish();

           }

       }).then(function(str){

           alert("您输入的是:" + str);

       });

});



ui.calc.click(()=>{

   let num1, num2, op;

   dialogs.input("请输入第一个数字")

       .then(n => {

           num1 = n;

           return dialogs.singleChoice("请选择运算", ["加", "减", "乘", "除", "幂"]);

       })

       .then(o => {

           op = o;

           return dialogs.input("请输入第二个数字");

        })

       .then(n => {

           num2 = n;

           var result;

           switch(op){

               case 0:

                   result = num1 + num2;

                   break;

               case 1:

                   result = num1 - num2;

                   break;

               case 2:

                   result = num1 * num2;

                   break;

               case 3:

                   result = num1 / num2;

                   break;

               case 4:

                   result = Math.pow(num1, num2);

                   break;

           }

           alert("运算结果", result);

       });

});


多媒体

免root屏幕录制


"ui";


importClass(android.content.Context);

importClass(android.hardware.display.DisplayManager);

importClass(android.media.MediaRecorder);

importClass(java.io.File);


runtime.requestPermissions(["WRITE_EXTERNAL_STORAGE", "READ_EXTERNAL_STORAGE", "RECORD_AUDIO"]);


mMediaProjectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);

mMediaRecorder = new MediaRecorder();

mVirtualDisplay = null;

saveDir = "/sdcard";

saveWidth = device.width;

saveHeight = device.height;

saveTime = 10 * 1000; // 单位:毫秒

isRunning = false;


ui.layout(

   <vertical>

       <appbar>

           <toolbar title="免root屏幕录制" />

       </appbar>

       <Switch id="permissions" text="音频录制及存储权限" checked="true" gravity="center"/>

       <frame gravity="center">

           <text text="AutoX" gravity="center" />

       </frame>

       <button text="免root屏幕录制" style="Widget.AppCompat.Button.Colored" id="button" />

   </vertical>

);


ui.button.click(function () {

   if (isRunning) {

       stopRecord();

       ui.button.setText("免root屏幕录制");

   } else {

       activity.startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), 666);

   }

});

// 申请权限

ui.permissions.on("check", function (checked) {

   if (checked) {

       runtime.requestPermissions(["WRITE_EXTERNAL_STORAGE", "READ_EXTERNAL_STORAGE", "RECORD_AUDIO"]);

   } else {

       toastLog("权限不足!");

   }

});

ui.emitter.on("resume", function () {

   ui.permissions.checked = true;

});


// 获取屏幕录制授权

ui.emitter.on("activity_result", (requestCode, resultCode, data) => {

   mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);

   if (mMediaProjection) {

       startRecord();

       ui.button.setText("视频录制中(点击停止)……");

       setTimeout(function () {

           stopRecord();

           ui.button.setText("免root屏幕录制");

       }, saveTime)

   }

});


events.on("exit", function () {

   stopRecord();

});


function startRecord() {

   if (mMediaProjection == null || isRunning) {

       return false;

   }

   file = new File(saveDir, "screen_record.mp4");

   mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

   mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);

   mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

   mMediaRecorder.setOutputFile(file.getAbsolutePath());

   mMediaRecorder.setVideoSize(saveWidth, saveHeight);

   mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

   mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

   mMediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);

   mMediaRecorder.setVideoFrameRate(30);

   try {

       mMediaRecorder.prepare();

   } catch (e) {

       toastLog(e);

   }

   mVirtualDisplay = mMediaProjection.createVirtualDisplay("免root屏幕录制", saveWidth, saveHeight, 1, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);

   mMediaRecorder.start();

   isRunning = true;

   return true;

}


function stopRecord() {

   if (!isRunning) {

       return false;

   }

   mMediaRecorder.stop();

   mMediaRecorder.reset();

   mVirtualDisplay.release();

   mMediaProjection.stop();

   isRunning = false;

   toastLog("录制结束!");

   return true;

}


音乐播放器


"ui";


ui.layout(

 <vertical>

   <text id="name" text="音乐播放器" textSize="22sp" textColor="#fbfbfe" bg="#00afff" w="*" gravity="center"></text>

   <button id="play">播放音乐</button>

   <button id="next">下一曲</button>

   <button id="pause">暂停</button>

 </vertical>

);

var musicDir = '/sdcard/Music';

if (!files.isDir(musicDir)) {

 toastLog(musicDir + "目录不存在!")

}

var musicFiles = files.listDir(musicDir, function (name) {

 return name.endsWith(".mp3") || name.endsWith(".wma") || name.endsWith(".wav")

});

var i = 0;

var musicPath = "";

if (musicFiles.length > 0) {

 musicPath = files.join(musicDir, musicFiles[i]);

 ui.name.setText(files.getNameWithoutExtension(musicPath));

} else {

 toastLog(musicDir + "目录下没有音频文件!")

}

ui.pause.click(function () {

 media.pauseMusic();

});

ui.next.click(function () {

 musicPath = files.join(musicDir, musicFiles[(i + 1) % musicFiles.length]);

 if (files.isFile(musicPath)) {

   ui.name.setText(files.getNameWithoutExtension(musicPath));

   media.playMusic(musicPath, 0.8);

 } else {

   toastLog(musicPath + "音频文件不存在!")

 }

}

);

ui.play.click(function () {

 if (media.isMusicPlaying()) {

   return true;

 } else {

   if (files.isFile(musicPath)) {

     ui.name.setText(files.getNameWithoutExtension(musicPath));

     media.playMusic(musicPath, 0.8);

   } else {

     toastLog(musicPath + "音频文件不存在!")

   }

 }

});

ui.emitter.on("pause", () => {

 if (media.isMusicPlaying()) {

   media.pauseMusic();

 }

});

ui.emitter.on("resume", () => {

 ui.post(function () {

   media.resumeMusic();

 }, 200);

});

events.on("exit", function () {

 media.stopMusic();

});


多线程

变量可见性实验


var running = true;


threads.start(function(){

   while(running){

       log("running = true");

   }

});


sleep(2000);

running = false;

console.info("running = false");


多线程按键监听


auto();


threads.start(function(){

   //在子线程中调用observeKey()从而使按键事件处理在子线程执行

   events.observeKey();

   events.on("key_down", function(keyCode, events){

       //音量键关闭脚本

       if(keyCode == keys.volume_up){

           exit();

       }

   });

});


toast("音量上键关闭脚本");


events.on("exit", function(){

   toast("脚本已结束");

});


while(true){

   log("脚本运行中...");

   sleep(2000);

}


多线程简单示例


//启动一个线程

threads.start(function(){

   //在线程中每隔1秒打印"线程1"

   while(true){

       log("线程1");

       sleep(1000);

   }

});


//启动另一个线程

threads.start(function(){

   //在线程中每隔2秒打印"线程1"

   while(true){

       log("线程2");

       sleep(2000);

   }

});


//在主线程中每隔3秒打印"主线程"

for(var i = 0; i < 10; i++){

   log("主线程");

   sleep(3000);

}

//打印100次后退出所有线程

threads.shutDownAll();


线程启动与关闭


//启动一个无限循环的线程

var thread = threads.start(function(){

   while(true){

       log("子线程运行中...");

       sleep(1000);

   }

});



//5秒后关闭线程

sleep(5000);

thread.interrupt();


原子变量


var i = threads.atomic();