跨设备随机数生成器:基于HarmonyOS的分布式随机数同步系统 原创

进修的泡芙
发布于 2025-6-18 21:04
浏览
0收藏

跨设备随机数生成器:基于HarmonyOS的分布式随机数同步系统

一、项目概述

本文实现一个基于HarmonyOS的随机数生成器系统,该系统不仅能在本地生成指定范围的随机数,还能通过分布式能力实现多设备间的随机数同步。借鉴《鸿蒙跨端U同步》中游戏多设备状态同步的设计思想,我们构建了一个可靠的随机数生成与同步机制,适用于多设备协同游戏、分布式抽奖等场景。

二、架构设计

±--------------------+ ±--------------------+
随机数生成UI <-----> 随机数同步服务
(RandomNumberUI) (RandomSyncService)
±---------±---------+ ±---------±---------+

±---------v----------+ ±---------v----------+
随机数生成引擎 分布式数据管理
(RandomEngine) (DistributedData)
±---------±---------+ ±---------±---------+

±---------v-----------------------------v----------+
HarmonyOS基础服务 |

±--------------------------------------------------+

三、核心代码实现
随机数生成引擎实现

public class RandomEngine {
private static final String TAG = “RandomEngine”;
private SecureRandom secureRandom;
private int minValue = 0;
private int maxValue = 100;

public RandomEngine() {
    try {
        // 使用更安全的随机数生成器
        secureRandom = SecureRandom.getInstance("SHA1PRNG");
        // 增加熵源
        secureRandom.setSeed(System.currentTimeMillis());

catch (NoSuchAlgorithmException e) {

        HiLog.error(TAG, "SecureRandom not available, using default");
        secureRandom = new SecureRandom();

}

// 设置随机数范围
public void setRange(int min, int max) {
    if (min >= max) {
        throw new IllegalArgumentException("Max must be greater than min");

this.minValue = min;

    this.maxValue = max;

// 生成随机数

public int generate() {
    return secureRandom.nextInt(maxValue - minValue + 1) + minValue;

// 批量生成随机数

public int[] generateBatch(int count) {
    int[] results = new int[count];
    for (int i = 0; i < count; i++) {
        results[i] = generate();

return results;

// 生成不重复的随机数序列

public int[] generateUnique(int count) {
    if (count > (maxValue - minValue + 1)) {
        throw new IllegalArgumentException("Count exceeds range size");

Set<Integer> set = new HashSet<>();

    while (set.size() < count) {
        set.add(generate());

return set.stream().mapToInt(Integer::intValue).toArray();

}

随机数同步服务实现

public class RandomSyncService {
private static final String TAG = “RandomSyncService”;
private static final String SYNC_CHANNEL = “random_sync”;
private static RandomSyncService instance;

private DistributedDataManager dataManager;
private RandomEngine randomEngine;
private Map<String, RandomListener> listeners = new HashMap<>();

private RandomSyncService(Context context) {
    this.dataManager = DistributedDataManagerFactory.getInstance()
        .createDistributedDataManager(context);
    this.randomEngine = new RandomEngine();
    initDataListener();

public static synchronized RandomSyncService getInstance(Context context) {

    if (instance == null) {
        instance = new RandomSyncService(context);

return instance;

private void initDataListener() {

    dataManager.registerDataChangeListener(SYNC_CHANNEL, new DataChangeListener() {
        @Override
        public void onDataChanged(String deviceId, String key, String value) {
            try {
                JSONObject randomJson = new JSONObject(value);
                String syncId = randomJson.getString("sync_id");
                int randomValue = randomJson.getInt("value");
                long timestamp = randomJson.getLong("timestamp");
                String sourceDevice = randomJson.getString("device_id");
                
                // 忽略本地设备发送的更新
                if (sourceDevice.equals(DistributedDeviceInfo.getLocalDeviceId())) {
                    return;

RandomListener listener = listeners.get(syncId);

                if (listener != null) {
                    listener.onRandomNumberReceived(syncId, randomValue, sourceDevice);

} catch (JSONException e) {

                HiLog.error(TAG, "Failed to parse random data");

}

    });

// 生成并同步随机数

public void generateAndSync(String syncId, int min, int max) {
    randomEngine.setRange(min, max);
    int randomValue = randomEngine.generate();
    syncRandomNumber(syncId, randomValue);

// 同步随机数

private void syncRandomNumber(String syncId, int value) {
    JSONObject randomJson = new JSONObject();
    try {
        randomJson.put("sync_id", syncId);
        randomJson.put("value", value);
        randomJson.put("timestamp", System.currentTimeMillis());
        randomJson.put("device_id", DistributedDeviceInfo.getLocalDeviceId());
        randomJson.put("version", getNextVersion());
        
        DistributedOptions options = new DistributedOptions();
        options.setPriority(DistributedOptions.Priority.HIGH);
        
        dataManager.putString(SYNC_CHANNEL, 
            randomJson.toString(), 
            DistributedDataManager.PUT_MODE_RELIABLE, 
            options);

catch (JSONException e) {

        HiLog.error(TAG, "Failed to serialize random data");

}

// 注册随机数监听器
public void registerListener(String syncId, RandomListener listener) {
    listeners.put(syncId, listener);

// 取消注册监听器

public void unregisterListener(String syncId) {
    listeners.remove(syncId);

public interface RandomListener {

    void onRandomNumberReceived(String syncId, int value, String fromDevice);

private int versionCounter = 0;

private synchronized int getNextVersion() {
    return ++versionCounter;

}

用户界面实现

public class RandomNumberSlice extends AbilitySlice {
private static final String TAG = “RandomNumberSlice”;
private static final String SYNC_ID = “global_random”;

private TextField minInput;
private TextField maxInput;
private Text resultDisplay;
private Text historyDisplay;
private RandomSyncService syncService;
private List<String> history = new ArrayList<>();

@Override
public void onStart(Intent intent) {
    super.onStart(intent);
    setUIContent(ResourceTable.Layout_random_layout);
    
    // 初始化服务
    syncService = RandomSyncService.getInstance(this);
    
    // 获取UI组件
    minInput = (TextField) findComponentById(ResourceTable.Id_min_input);
    maxInput = (TextField) findComponentById(ResourceTable.Id_max_input);
    Button generateBtn = (Button) findComponentById(ResourceTable.Id_generate_btn);
    Button syncBtn = (Button) findComponentById(ResourceTable.Id_sync_btn);
    resultDisplay = (Text) findComponentById(ResourceTable.Id_result_display);
    historyDisplay = (Text) findComponentById(ResourceTable.Id_history_display);
    
    // 设置按钮事件
    generateBtn.setClickedListener(component -> generateLocal());
    syncBtn.setClickedListener(component -> generateAndSync());
    
    // 注册同步监听器
    syncService.registerListener(SYNC_ID, new RandomSyncService.RandomListener() {
        @Override
        public void onRandomNumberReceived(String syncId, int value, String fromDevice) {
            getUITaskDispatcher().asyncDispatch(() -> {
                String message = "来自" + fromDevice + "的随机数: " + value;
                addHistory(message);
                resultDisplay.setText(String.valueOf(value));
            });

});

private void generateLocal() {

    try {
        int min = Integer.parseInt(minInput.getText());
        int max = Integer.parseInt(maxInput.getText());
        
        RandomEngine engine = new RandomEngine();
        engine.setRange(min, max);
        int result = engine.generate();
        
        resultDisplay.setText(String.valueOf(result));
        addHistory("本地生成: " + result);

catch (NumberFormatException e) {

        showToast("请输入有效的数字范围");

catch (IllegalArgumentException e) {

        showToast(e.getMessage());

}

private void generateAndSync() {
    try {
        int min = Integer.parseInt(minInput.getText());
        int max = Integer.parseInt(maxInput.getText());
        
        syncService.generateAndSync(SYNC_ID, min, max);
        addHistory("已发送生成请求...");

catch (NumberFormatException e) {

        showToast("请输入有效的数字范围");

catch (IllegalArgumentException e) {

        showToast(e.getMessage());

}

private void addHistory(String entry) {
    history.add(0, entry); // 添加到开头
    if (history.size() > 10) {
        history.remove(history.size() - 1); // 保留最近10条

StringBuilder builder = new StringBuilder(“历史记录:\n”);

    for (String item : history) {
        builder.append("• ").append(item).append("\n");

historyDisplay.setText(builder.toString());

private void showToast(String message) {

    new ToastDialog(getContext())
        .setText(message)
        .show();

@Override

protected void onStop() {
    super.onStop();
    // 取消注册监听器
    syncService.unregisterListener(SYNC_ID);

}

XML布局文件

<DirectionalLayout
xmlns:ohos=“http://schemas.huawei.com/res/ohos
ohos:width=“match_parent”
ohos:height=“match_parent”
ohos:orientation=“vertical”
ohos:padding=“24vp”>

<Text
    ohos:width="match_parent"
    ohos:height="wrap_content"
    ohos:text="跨设备随机数生成器"
    ohos:text_size="24fp"
    ohos:margin_bottom="16vp"/>
    
<DirectionalLayout
    ohos:width="match_parent"
    ohos:height="wrap_content"
    ohos:orientation="horizontal"
    ohos:margin_bottom="16vp">
    
    <TextField
        ohos:id="$+id:min_input"
        ohos:width="100vp"
        ohos:height="60vp"
        ohos:hint="最小值"
        ohos:text="0"/>
        
    <Text
        ohos:width="wrap_content"
        ohos:height="60vp"
        ohos:text="到"
        ohos:text_size="18fp"
        ohos:margin_left="8vp"
        ohos:margin_right="8vp"
        ohos:alignment="center"/>
        
    <TextField
        ohos:id="$+id:max_input"
        ohos:width="100vp"
        ohos:height="60vp"
        ohos:hint="最大值"
        ohos:text="100"/>
</DirectionalLayout>

<Button
    ohos:id="$+id:generate_btn"
    ohos:width="match_parent"
    ohos:height="60vp"
    ohos:text="生成随机数"
    ohos:margin_bottom="8vp"/>
    
<Button
    ohos:id="$+id:sync_btn"
    ohos:width="match_parent"
    ohos:height="60vp"
    ohos:text="生成并同步到所有设备"
    ohos:margin_bottom="16vp"/>
    
<Text
    ohos:id="$+id:result_display"
    ohos:width="match_parent"
    ohos:height="100vp"
    ohos:text_size="36fp"
    ohos:text_alignment="center"
    ohos:text="?"
    ohos:margin_bottom="16vp"/>
    
<ScrollView
    ohos:width="match_parent"
    ohos:height="200vp">
    
    <Text
        ohos:id="$+id:history_display"
        ohos:width="match_parent"
        ohos:height="match_parent"
        ohos:text="历史记录将显示在这里..."/>
</ScrollView>

</DirectionalLayout>

Ability配置 (config.json)

“abilities”: [

“name”: “RandomNumberAbility”,

  "type": "page",
  "label": "RandomNumber",
  "icon": "$media:icon",
  "launchType": "standard",
  "backgroundModes": ["dataSync"]

]

四、与《鸿蒙跨端U同步》的技术关联

本项目借鉴了游戏多设备同步的以下关键技术:
状态同步模型:类似游戏中玩家状态的实时同步,随机数通过JSON格式广播

设备标识:使用设备ID区分不同来源的随机数

版本控制:引入版本号解决潜在的冲突问题

可靠传输:使用高优先级的数据传输确保同步成功率

增强的同步逻辑(借鉴游戏同步机制):

// 增强的随机数同步方法
private void syncRandomNumber(String syncId, int value) {
JSONObject randomJson = new JSONObject();
try {
randomJson.put(“sync_id”, syncId);
randomJson.put(“value”, value);
randomJson.put(“timestamp”, System.currentTimeMillis());
randomJson.put(“device_id”, DistributedDeviceInfo.getLocalDeviceId());
randomJson.put(“version”, getNextVersion());

    // 增加随机数校验码
    randomJson.put("checksum", calculateChecksum(value));
    
    // 设置传输选项
    DistributedOptions options = new DistributedOptions();
    options.setPriority(DistributedOptions.Priority.HIGH);
    options.setTimeToLive(10000); // 10秒有效期
    options.setRetryCount(3); // 重试3次
    
    // 使用可靠传输
    dataManager.putString(SYNC_CHANNEL, 
        randomJson.toString(), 
        DistributedDataManager.PUT_MODE_RELIABLE, 
        options);

catch (JSONException e) {

    HiLog.error(TAG, "Failed to serialize random data");

}

// 校验随机数数据完整性
private boolean validateRandomData(JSONObject randomJson) {
try {
int value = randomJson.getInt(“value”);
int checksum = randomJson.getInt(“checksum”);
return checksum == calculateChecksum(value);
catch (JSONException e) {

    return false;

}

// 简单的校验码计算
private int calculateChecksum(int value) {
return (value ^ 0x55AA) + 12345;

五、项目特色与创新点
安全随机数生成:使用SecureRandom提供更安全的随机数

跨设备同步:随机数状态可在多设备间实时同步

历史记录:完整记录所有生成的随机数

可靠传输:借鉴游戏同步的重试机制,确保消息送达

范围控制:支持自定义随机数范围

六、应用场景
多设备协同游戏:同步游戏中的随机事件

分布式抽奖系统:多终端同时开奖

随机分组系统:跨设备的人员随机分组

教学演示工具:展示随机数生成原理

七、总结

本随机数生成器系统实现了以下功能:
安全生成指定范围的随机数

多设备间随机数实时同步

生成历史记录查看

可靠的数据传输机制

通过借鉴游戏中的状态同步技术,我们构建了一个可靠的跨设备随机数生成系统。未来可扩展功能包括:
更复杂的随机数分布(正态分布、泊松分布等)

随机数种子同步

多设备协同随机数生成算法

区块链技术增强随机数的不可篡改性

这个项目展示了如何将游戏中的同步技术应用于实用工具开发,为构建更复杂的分布式应用提供了基础。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐