Skip to content

模板示例 ​

三个可以直接抄的例子,从简到复杂。

示例 1:最小可用 ​

验证环境是否正常。生成当天 60 分钟,全部集中在 12 点。

manifest.json

json
{ "id": "mini", "name": "最小模板", "permissions": ["write:usage"], "apiLevel": 1 }

main.js

js
function buildUI() {
  return { sections: [{ card: [{ type: 'text', text: '最小模板' }] }] };
}

function listDates() { return [util.today()]; }

function generate(date) {
  var hours = [];
  for (var i = 0; i < 24; i++) hours.push(i === 12 ? 60 : 0);
  return {
    total: 60,
    hourly: hours,
    apps: [],
    eyes: { total: 0, categories: {} },
    unlocks: 0,
    unlockHourly: hours.slice()
  };
}

示例 2:游戏日(带界面交互) ​

工作日晚上的重度游戏数据,界面可调时长、夜间零使用、时段曲线、日期列表。

manifest.json

json
{
  "id": "game-day",
  "name": "游戏日",
  "author": "demo",
  "version": "1.0",
  "description": "工作日晚上集中玩游戏",
  "permissions": ["write:usage"],
  "apiLevel": 1
}

main.js

js
var state = {
  dailyMinutes: 240,
  nightZero: true,
  hourWeights: [0,0,0,0,0,0,0,2,4,5,4,4,7,6,5,5,6,9,14,18,20,17,9,3],
  dates: [],
  games: ['com.tencent.tmgp.sgame', 'com.tencent.tmgp.pubgmhd']
};

function onLoad() {
  if (!state.dates || state.dates.length === 0) state.dates = [util.today()];
  var saved = store.get('state');
  if (saved) for (var k in saved) state[k] = saved[k];
}

function buildUI() {
  return {
    sections: [
      { title: '概览', card: [
        { type: 'bigValue', title: '预计日均',
          value: util.formatDuration(state.dailyMinutes),
          summary: state.nightZero ? '已开启夜间零使用' : '' }
      ]},
      { title: '时间', card: [
        { type: 'row', title: '日均时长', value: util.formatDuration(state.dailyMinutes), onClick: 'editDaily' },
        { type: 'switch', title: '夜间零使用', summary: '0-6 点不产生数据', value: state.nightZero, onChange: 'setNight' }
      ]},
      { title: '权重', card: [
        { type: 'chart24', title: '时段权重', values: state.hourWeights, onChange: 'setWeights' },
        { type: 'text', text: '晚上 18-22 点权重最高' }
      ]},
      { title: '日期', card: [
        { type: 'plusList', title: '日期', items: state.dates, onAdd: 'addDate', onDelete: 'delDate' }
      ]},
      { card: [{ type: 'button', text: '保存参数', onClick: 'saveState' }] }
    ]
  };
}

function listDates() { return state.dates; }

function generate(date) {
  var cap = [];
  for (var i = 0; i < 24; i++) cap.push(60);
  if (state.nightZero) for (var i = 0; i < 6; i++) cap[i] = 0;

  var total = Math.round(calc.jitter(state.dailyMinutes, 10));
  var hourly = calc.fill(total, state.hourWeights, cap);
  var sum = calc.sum(hourly);

  var perApp = calc.largestRemainder(sum, [3, 1]);
  var apps = state.games.map(function (pkg, i) {
    return { pkg: pkg, name: '游戏' + (i + 1), minutes: perApp[i], hourly: [] };
  });

  var day = {
    total: sum,
    hourly: hourly,
    apps: apps,
    eyes: {
      total: Math.round(sum * 0.7),
      categories: { healthy: 30, dimLight: 20, lyingDown: 15, overUse: 40, upClose: 15 }
    },
    unlocks: 100,
    unlockHourly: calc.largestRemainder(100, state.hourWeights)
  };

  data.writeDay(date, day, 'overwrite');
  return day;
}

// ---------------- 回调
function editDaily() { ui.input('日均时长(分钟)', String(state.dailyMinutes), '', 'onDailyInput'); }
function onDailyInput(v) {
  var n = parseInt(v, 10);
  if (n > 0 && n <= 1440) { state.dailyMinutes = n; ui.refresh(); }
}
function setNight(v) { state.nightZero = v; ui.refresh(); }
function setWeights(values) { state.hourWeights = values; }
function addDate() { ui.pickDate('onDatesPicked'); }
function onDatesPicked(ranges) {
  for (var i = 0; i < ranges.length; i++) {
    var s = ranges[i].start;
    if (state.dates.indexOf(s) < 0) state.dates.push(s);
  }
  ui.refresh();
}
function delDate(i) { state.dates.splice(i, 1); ui.refresh(); }
function saveState() { store.set('state', state); ui.alert('已保存', '参数已存入模板私有存储'); }

示例 3:联网拉权重 ​

从外部 API 拿 24 小时权重,失败时回落默认曲线。

manifest.json

json
{
  "id": "remote-weights",
  "name": "远程权重",
  "permissions": ["write:usage", "network"],
  "apiLevel": 1
}

main.js

js
var DEFAULT = [0,0,0,0,0,0,1,3,6,8,6,6,9,7,5,5,6,8,12,16,18,16,10,4];

var state = {
  dailyMinutes: 200,
  weights: DEFAULT.slice(),
  dates: [util.today()]
};

function loadWeights() {
  try {
    var r = http.getJson('https://example.com/api/weights', { timeout: 20000 });
    if (r && r.weights && r.weights.length === 24) {
      state.weights = r.weights;
      ui.alert('已更新', '从服务器拉到新的时段权重');
      ui.refresh();
      return;
    }
    ui.alert('格式不对', '返回的 weights 不是 24 个数');
  } catch (e) {
    ui.alert('拉取失败', e.message);
  }
}

function buildUI() {
  return {
    sections: [
      { title: '参数', card: [
        { type: 'row', title: '日均时长', value: util.formatDuration(state.dailyMinutes), onClick: 'editDaily' },
        { type: 'row', title: '从服务器拉权重', value: '', arrow: true, onClick: 'loadWeights' },
        { type: 'chart24', title: '当前权重', values: state.weights, onChange: 'setWeights' }
      ]},
      { title: '日期', card: [
        { type: 'plusList', title: '日期', items: state.dates, onAdd: 'addDate', onDelete: 'delDate' }
      ]}
    ]
  };
}

function listDates() { return state.dates; }

function generate(date) {
  var cap = [];
  for (var i = 0; i < 24; i++) cap.push(60);
  var total = state.dailyMinutes;
  var hourly = calc.fill(total, state.weights, cap);
  var sum = calc.sum(hourly);
  var day = {
    total: sum,
    hourly: hourly,
    apps: [],
    eyes: { total: Math.round(sum * 0.6), categories: { healthy: 40, dimLight: 20, lyingDown: 10, overUse: 20, upClose: 10 } },
    unlocks: 80,
    unlockHourly: calc.largestRemainder(80, state.weights)
  };
  data.writeDay(date, day, 'overwrite');
  return day;
}

function editDaily() { ui.input('日均时长(分钟)', String(state.dailyMinutes), '', 'onDailyInput'); }
function onDailyInput(v) { var n = parseInt(v, 10); if (n > 0 && n <= 1440) { state.dailyMinutes = n; ui.refresh(); } }
function setWeights(v) { state.weights = v; }
function addDate() { ui.pickDate('onDatesPicked'); }
function onDatesPicked(ranges) {
  for (var i = 0; i < ranges.length; i++) {
    if (state.dates.indexOf(ranges[i].start) < 0) state.dates.push(ranges[i].start);
  }
  ui.refresh();
}
function delDate(i) { state.dates.splice(i, 1); ui.refresh(); }

常见坑 ​

坑现象解决
忘了 listDates生成按钮点了报错补上,返回非空数组
data.writeDay 但没声明 write:usage生成失败,提示未声明权限manifest 加权限
数据不自洽统计页柱子、数字对不上用 calc.* 分配,别手写随机
hourly 某小时 > 60图表溢出用 calc.fill(total, weights, calc.capacity(ranges))
回调里改了值但界面没变界面不刷新加 ui.refresh()
拖动滑条时界面卡slider 的 onChange 里 refresh 了拖动中不要 refresh
console.log 没输出引擎没有 console用 ui.alert 调试

仅供学习与界面体验使用