android设计——功能临时开启与永久管控

摘要:本文基于android平台,设计一种框架并实现对功能的管控和临时的开启。首先,使用SharedPreferences来保存默认状态,因为需要持久化存储,即使在重启或掉电后也能恢复。默认状态是永久开启或关闭,所以需要有一个地方存储当前的默认状态:表示是永久开启还是永久关闭。其次,创建一个BroadcastReceiver,监听指定的广播动作。当接收到广播时,解析三个参数,并进行参数校验。例如,检查mode是否为“permanent”或“temporary”,status是否为“enable”或“disable”,time是否为有效的正整数(当mode是临时且status是开启时)。根据当前的默认状态和接收到的参数,执行相应的逻辑。最后,处理临时任务的生命周期。例如,当设备重启或掉电时,临时任务会被取消,但默认状态保持不变。因此,在应用启动时,应该检查是否有正在进行的临时任务,但根据需求,重启后不需要处理未完成的倒计时,直接恢复默认状态即可。另外,当处于临时开启状态时,如果再次收到临时开启的请求,需要取消现有的倒计时,重新开始新的倒计时。这需要管理当前的倒计时实例,可能使用一个成员变量来持有CountDownTimer,并在需要时取消它。

在AndroidManifest.xml注册广播接收器:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver 
    android:name=".MyReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.settings.XXX_XXX" />
     </intent-filter>
</receiver>

<receiver
    android:name=".MyReceiver$BootReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

实现代码(详见注释说明):

管控逻辑:

  1. 功能默认永久关闭
  2. 功能处于永久开启状态时:
    (1) 收到永久关闭请求时,永久关闭
    (2) 收到永久开启/临时开启请求时,显示已永久开启
  3. 功能处于永久关闭状态时:
    (1) 收到永久开启请求时,永久开启
    (2) 收到临时开启请求时,临时开启,倒计时,显示信息(临时开启,功能持续时间n分钟)
  4. 功能处于临时开启状态时:
    (1) 收到临时开启请求时,刷新计时时间,显示信息(功能已经处于临时开启状态,更新持续时间n分钟)
    (2) 收到永久开启/关闭请求时,永久开启/关闭
    (3) 倒计时时间到或者重启设备或者掉电后,开机恢复默认状态
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    private static final String PREF_NAME = "xxx_config";
    private static final String KEY_MODE = "permanent_mode";  // 只保存永久状态
    private static final String KEY_STATUS = "permanent_status";
    
    // 临时任务相关(内存存储)
    private static CountDownTimer currentTimer;
    private static String tempBaseStatus; // 临时状态的基础状态

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!"android.intent.settings.XXX_XXX".equals(intent.getAction())) return;

        // 解析参数
        String mode = intent.getStringExtra("mode");
        String status = intent.getStringExtra("status");
        int time = intent.getIntExtra("time", 0);

        if (!validateParams(mode, status, time)) {
            Toast.makeText(context, "参数错误", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String savedMode = sp.getString(KEY_MODE, "permanent");
        String savedStatus = sp.getString(KEY_STATUS, "disable");

        handleCommand(context, mode, status, time, sp, savedStatus);
    }

    private boolean validateParams(String mode, String status, int time) {
        if (!"permanent".equals(mode) && !"temporary".equals(mode)) return false;
        if (!"enable".equals(status) && !"disable".equals(status)) return false;
        if ("temporary".equals(mode) && "enable".equals(status) && time <= 0) return false;
        return true;
    }

    private void handleCommand(Context context, String cmdMode, String cmdStatus, int time,
                              SharedPreferences sp, String savedStatus) {
        // 当前是否有临时任务
        boolean hasTempTask = (currentTimer != null);

        if ("permanent".equals(cmdMode)) {
            handlePermanentCommand(context, cmdStatus, sp, savedStatus, hasTempTask);
        } else {
            handleTemporaryCommand(context, cmdStatus, time, sp, savedStatus, hasTempTask);
        }
    }

    private void handlePermanentCommand(Context context, String cmdStatus, 
                                       SharedPreferences sp, String savedStatus,
                                       boolean hasTempTask) {
        if (hasTempTask) {
            cancelCurrentTimer();
            revertToSavedState(context, sp);
        }

        if (!savedStatus.equals(cmdStatus)) {
            updatePermanentState(sp, cmdStatus);
            if ("enable".equals(cmdStatus)) {
                performEnableAction(context);
            } else {
                performDisableAction(context);
            }
        } else {
            Toast.makeText(context, "状态未变化", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleTemporaryCommand(Context context, String cmdStatus, int time,
                                       SharedPreferences sp, String savedStatus,
                                       boolean hasTempTask) {
        if (!"enable".equals(cmdStatus)) return;

        if (hasTempTask) {
            cancelCurrentTimer();
        } else {
            tempBaseStatus = savedStatus; // 记录基础状态
        }

        startTemporaryTask(context, time, sp);
        performEnableAction(context);
    }

    private void startTemporaryTask(Context context, int time, SharedPreferences sp) {
        currentTimer = new CountDownTimer(time * 1000L, 1000) {
            public void onTick(long millisUntilFinished) {}

            public void onFinish() {
                revertToSavedState(context, sp);
                currentTimer = null;
            }
        }.start();
    }

    private void revertToSavedState(Context context, SharedPreferences sp) {
        String savedStatus = sp.getString(KEY_STATUS, "disable");
        if ("disable".equals(savedStatus)) {
            performDisableAction(context);
        }
    }

    private void updatePermanentState(SharedPreferences sp, String status) {
        sp.edit()
                .putString(KEY_MODE, "permanent")
                .putString(KEY_STATUS, status)
                .apply();
    }

    private void cancelCurrentTimer() {
        if (currentTimer != null) {
            currentTimer.cancel();
            currentTimer = null;
        }
    }

    // 开机状态恢复
    public static class BootReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            String status = sp.getString(KEY_STATUS, "disable");

            if ("enable".equals(status)) {
                performEnableAction(context);
            } else {
                performDisableAction(context);
            }
        }
    }

    // 实际功能操作(示例)
    private static void performEnableAction(Context context) {
        // 系统级操作
        Toast.makeText(context, "功能已启用", Toast.LENGTH_SHORT).show();
    }

    private static void performDisableAction(Context context) {
        // 系统级操作
        Toast.makeText(context, "功能已禁用", Toast.LENGTH_SHORT).show();
    }
}

你可能感兴趣的:(代码小技巧,android)