Commit ac1ee685 authored by leichao.gao's avatar leichao.gao

update

parent 7feeaebf
...@@ -8,6 +8,15 @@ ...@@ -8,6 +8,15 @@
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- fcm 添加以下权限 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<application <application
android:name=".MyApplication" android:name=".MyApplication"
android:allowBackup="true" android:allowBackup="true"
...@@ -159,6 +168,27 @@ ...@@ -159,6 +168,27 @@
<meta-data <meta-data
android:name="com.facebook.sdk.ApplicationId" android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" /> android:value="@string/facebook_app_id" />
<service
android:name=".fcm.FcmService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service> <!-- 添加以下接收器 -->
<!-- 注册广播 -->
<receiver
android:name=".fcm.FcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.test.easy.cleanerjunk" />
</intent-filter>
</receiver>
</application> </application>
</manifest> </manifest>
\ No newline at end of file
...@@ -16,7 +16,7 @@ import com.base.datarecovery.databinding.ActivityLayoutResultBinding ...@@ -16,7 +16,7 @@ import com.base.datarecovery.databinding.ActivityLayoutResultBinding
import com.base.datarecovery.help.BaseActivity import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.KotlinExt.toFormatSize import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.utils.BarUtils import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.SPUtils import com.base.datarecovery.utils.AppPreferences
class ResultActivity : BaseActivity<ActivityLayoutResultBinding>() { class ResultActivity : BaseActivity<ActivityLayoutResultBinding>() {
...@@ -60,7 +60,7 @@ class ResultActivity : BaseActivity<ActivityLayoutResultBinding>() { ...@@ -60,7 +60,7 @@ class ResultActivity : BaseActivity<ActivityLayoutResultBinding>() {
} else { } else {
binding.tvInfo.text = "No junk files found." binding.tvInfo.text = "No junk files found."
} }
SPUtils.getInstance().put("last_use_junk_cleaner", System.currentTimeMillis()) AppPreferences.getInstance().put("last_use_junk_cleaner", System.currentTimeMillis())
} }
else -> {} else -> {}
......
...@@ -11,7 +11,7 @@ import com.base.datarecovery.bean.ConstObject.JUNK_CLEANER ...@@ -11,7 +11,7 @@ import com.base.datarecovery.bean.ConstObject.JUNK_CLEANER
import com.base.datarecovery.bean.ConstObject.REPEAT_PHOTOS import com.base.datarecovery.bean.ConstObject.REPEAT_PHOTOS
import com.base.datarecovery.bean.ConstObject.SCREENSHOT_CLEANER import com.base.datarecovery.bean.ConstObject.SCREENSHOT_CLEANER
import com.base.datarecovery.databinding.ItemResultFunBinding import com.base.datarecovery.databinding.ItemResultFunBinding
import com.base.datarecovery.utils.SPUtils import com.base.datarecovery.utils.AppPreferences
import com.base.datarecovery.view.XmlEx.inflate import com.base.datarecovery.view.XmlEx.inflate
import java.util.Collections import java.util.Collections
...@@ -64,7 +64,7 @@ class AppFunctionAdapter(val click: (name: String) -> Unit) : ...@@ -64,7 +64,7 @@ class AppFunctionAdapter(val click: (name: String) -> Unit) :
fun updateListPosition() { fun updateListPosition() {
//本次进入结果页,判断使用垃圾的功能是否超过5分钟 //本次进入结果页,判断使用垃圾的功能是否超过5分钟
val lastUseJunkCleaner = SPUtils.getInstance().getLong("last_use_junk_cleaner", 0) val lastUseJunkCleaner = AppPreferences.getInstance().getLong("last_use_junk_cleaner", 0)
if ((System.currentTimeMillis() - lastUseJunkCleaner) >= 60 * 5 * 1000) { if ((System.currentTimeMillis() - lastUseJunkCleaner) >= 60 * 5 * 1000) {
} else { } else {
Collections.rotate(list, list.size - 1) Collections.rotate(list, list.size - 1)
......
package com.base.datarecovery.bean package com.base.datarecovery.bean
import com.base.datarecovery.utils.SPUtils import com.base.datarecovery.utils.AppPreferences
object ConstObject { object ConstObject {
...@@ -24,56 +24,56 @@ object ConstObject { ...@@ -24,56 +24,56 @@ object ConstObject {
var ifAgreePrivacy = false var ifAgreePrivacy = false
get() { get() {
return SPUtils.getInstance().getBoolean("ifAgreePrivacy", field) return AppPreferences.getInstance().getBoolean("ifAgreePrivacy", field)
} }
set(value) { set(value) {
field = value field = value
SPUtils.getInstance().put("ifAgreePrivacy", value, true) AppPreferences.getInstance().put("ifAgreePrivacy", value, true)
} }
var rememberOption = false var rememberOption = false
get() { get() {
return SPUtils.getInstance().getBoolean("rememberOption", field) return AppPreferences.getInstance().getBoolean("rememberOption", field)
} }
set(value) { set(value) {
field = value field = value
SPUtils.getInstance().put("rememberOption", value, true) AppPreferences.getInstance().put("rememberOption", value, true)
} }
var rememberRemove = false var rememberRemove = false
get() { get() {
return SPUtils.getInstance().getBoolean("rememberRemove", field) return AppPreferences.getInstance().getBoolean("rememberRemove", field)
} }
set(value) { set(value) {
field = value field = value
SPUtils.getInstance().put("rememberRemove", value, true) AppPreferences.getInstance().put("rememberRemove", value, true)
} }
var privacyPinPassword = "" var privacyPinPassword = ""
get() { get() {
return SPUtils.getInstance().getString("privacyPinPassword", field) return AppPreferences.getInstance().getString("privacyPinPassword", field)
} }
set(value) { set(value) {
field = value field = value
SPUtils.getInstance().put("privacyPinPassword", value, true) AppPreferences.getInstance().put("privacyPinPassword", value, true)
} }
var stayNotification = true var stayNotification = true
get() { get() {
return SPUtils.getInstance().getBoolean("stayNotification", field) return AppPreferences.getInstance().getBoolean("stayNotification", field)
} }
set(value) { set(value) {
field = value field = value
SPUtils.getInstance().put("stayNotification", value, true) AppPreferences.getInstance().put("stayNotification", value, true)
} }
var fcmNotification = true var fcmNotification = true
get() { get() {
return SPUtils.getInstance().getBoolean("fcmNotification", field) return AppPreferences.getInstance().getBoolean("fcmNotification", field)
} }
set(value) { set(value) {
field = value field = value
SPUtils.getInstance().put("fcmNotification", value, true) AppPreferences.getInstance().put("fcmNotification", value, true)
} }
} }
\ No newline at end of file
...@@ -4,7 +4,7 @@ import android.app.NotificationManager ...@@ -4,7 +4,7 @@ import android.app.NotificationManager
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import com.base.datarecovery.utils.SPUtils import com.base.datarecovery.utils.AppPreferences
class CloseNotificationReceiver : BroadcastReceiver() { class CloseNotificationReceiver : BroadcastReceiver() {
companion object { companion object {
...@@ -17,7 +17,7 @@ class CloseNotificationReceiver : BroadcastReceiver() { ...@@ -17,7 +17,7 @@ class CloseNotificationReceiver : BroadcastReceiver() {
if (action != null && action == "CANCEL_NOTIFICATION") { if (action != null && action == "CANCEL_NOTIFICATION") {
var notificationId = intent.getIntExtra(NotificationId, 0) var notificationId = intent.getIntExtra(NotificationId, 0)
val notificationManager = context!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager = context!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val actionS: Int = SPUtils.getInstance().getInt("actionS", 0) val actionS: Int = AppPreferences.getInstance().getInt("actionS", 0)
if (actionS == 0) { if (actionS == 0) {
notificationId = 0 notificationId = 0
} }
......
package com.base.datarecovery.fcm;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;
public class FCMManager {
public static void initFirebase(Context context) {
FirebaseApp.initializeApp(context);
}
public static void subscribeToTopic(String topic) {
FirebaseMessaging.getInstance().subscribeToTopic(topic)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("FCMUtil", "suc");
} else {
Log.d("FCMUtil", "fail");
}
}
});
}
public static void unsubscribeFromTopic(String topic) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(topic)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
} else {
}
}
});
}
}
package com.base.datarecovery.fcm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class FcmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
package com.base.datarecovery.fcm;
import android.util.Log;
import androidx.annotation.NonNull;
import com.base.datarecovery.utils.AppPreferences;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FcmService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
long pushStayTime = remoteMessage.getData().get("push_stay_time") != null ? Long.parseLong(remoteMessage.getData().get("push_stay_time")) : 0;
int open = remoteMessage.getData().get("open") != null ? Integer.parseInt(remoteMessage.getData().get("open")) : 0;
int num = remoteMessage.getData().get("num") != null ? Integer.parseInt(remoteMessage.getData().get("num")) : 0;
long delay = remoteMessage.getData().get("delay") != null ? Long.parseLong(remoteMessage.getData().get("delay")) : 0L;
int actionS = remoteMessage.getData().get("actionS") != null ? Integer.parseInt(remoteMessage.getData().get("actionS")) : 0;
int lockS = remoteMessage.getData().get("lockS") != null ? Integer.parseInt(remoteMessage.getData().get("lockS")) : 0;
int adClickCount = remoteMessage.getData().get("adClickCount") != null ? Integer.parseInt(remoteMessage.getData().get("adClickCount")) : 0;
int adShowCount = remoteMessage.getData().get("adShowCount") != null ? Integer.parseInt(remoteMessage.getData().get("adShowCount")) : 0;
int adInterval = remoteMessage.getData().get("adInterval") != null ? Integer.parseInt(remoteMessage.getData().get("adInterval")) : 0;
int interval = remoteMessage.getData().get("notificationInterval") != null ? Integer.parseInt(remoteMessage.getData().get("notificationInterval")) : 0;
int timerS = remoteMessage.getData().get("timerS") != null ? Integer.parseInt(remoteMessage.getData().get("timerS")) : 1;
int timerDelay = remoteMessage.getData().get("timerDelay") != null ? Integer.parseInt(remoteMessage.getData().get("timerDelay")) : 1;
int timerInterval = remoteMessage.getData().get("timerInterval") != null ? Integer.parseInt(remoteMessage.getData().get("timerInterval")) : 5;
AppPreferences.getInstance().put("actionS", actionS);
AppPreferences.getInstance().put("open", open);
AppPreferences.getInstance().put("num", num);
AppPreferences.getInstance().put("delay", delay);
AppPreferences.getInstance().put("lockS", lockS);
AppPreferences.getInstance().put("notification_interval", interval);
AppPreferences.getInstance().put("timerS", timerS);
AppPreferences.getInstance().put("timerDelay", timerDelay);
AppPreferences.getInstance().put("timerInterval", timerInterval);
if (timerS == 0) {
RecoveryTimerManager.getInstance().stopTaskTimer();
} else {
if (!RecoveryTimerManager.getInstance().isTaskTimerActive()) {
RecoveryTimerManager.getInstance().scheduleTask(timerDelay * 60000, timerInterval * 60000);
}
}
// AdmobUtils.INSTANCE.setAdDisplayInterval(adInterval);
// AdDisplayUtils.getInstance().setMaxAdDisplayCount(adShowCount);
// AdDisplayUtils.getInstance().setMaxAdClickCount(adClickCount);
//
// EventUtils.INSTANCE.event("FCM_Received",null,null,false);
//
// NotificationUtil.sendNotification(MyApplication.context);
Log.d("FcmService", remoteMessage.getData().toString());
}
}
package com.base.datarecovery.fcm;
import androidx.annotation.NonNull;
import com.base.datarecovery.utils.AppPreferences;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.Map;
public class MessagingService extends FirebaseMessagingService {
private static final String TAG = "MessagingService";
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
updateSharedPreferences(remoteMessage.getData());
manageTimerBasedOnMessage(remoteMessage.getData());
sendLocalNotification();
}
private void updateSharedPreferences(@NonNull Map<String, String> data) {
for (Map.Entry<String, String> entry : data.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// 对于整型值使用parseInt, 长整型使用parseLong
AppPreferences.getInstance().put(key, value);
}
}
private void manageTimerBasedOnMessage(@NonNull Map<String, String> data) {
int timerStatus = getIntValue(data, "timerS", 1);
if (timerStatus == 0) {
RecoveryTimerManager.getInstance().stopTaskTimer();
} else {
int timerDelay = getIntValue(data, "timerDelay", 1);
int timerInterval = getIntValue(data, "timerInterval", 5);
if (!RecoveryTimerManager.getInstance().isTaskTimerActive()) {
RecoveryTimerManager.getInstance().scheduleTask(timerDelay * 60000, timerInterval * 60000);
}
}
}
private int getIntValue(@NonNull Map<String, String> data, String key, int defaultValue) {
String value = data.get(key);
return value != null ? Integer.parseInt(value) : defaultValue;
}
// Consider implementing this method if local notifications are needed
private void sendLocalNotification() {
// ...
}
}
\ No newline at end of file
...@@ -19,7 +19,7 @@ import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_PHOTOS ...@@ -19,7 +19,7 @@ import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_PHOTOS
import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_VIDEOS import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_VIDEOS
import com.base.datarecovery.bean.ConstObject.ID_SCREENSHOT_CLEAN import com.base.datarecovery.bean.ConstObject.ID_SCREENSHOT_CLEAN
import com.base.datarecovery.bean.ConstObject.ID_SIMILAR_IMAGE import com.base.datarecovery.bean.ConstObject.ID_SIMILAR_IMAGE
import com.base.datarecovery.utils.SPUtils import com.base.datarecovery.utils.AppPreferences
import java.util.Random import java.util.Random
/** /**
...@@ -170,11 +170,11 @@ object NotificationUtil { ...@@ -170,11 +170,11 @@ object NotificationUtil {
builder.setCustomBigContentView(bigRemoteViews) builder.setCustomBigContentView(bigRemoteViews)
// Show the notification // Show the notification
if (SPUtils.getInstance().getInt("actionS", 1) == 1) { if (AppPreferences.getInstance().getInt("actionS", 1) == 1) {
notificationManager.notify(intent.getIntExtra("actionId", actionId), builder.build()) notificationManager.notify(intent.getIntExtra("actionId", actionId), builder.build())
} else { } else {
notificationManager.notify(actionId, builder.build()) notificationManager.notify(actionId, builder.build())
} }
SPUtils.getInstance().put("last_notification_time", System.currentTimeMillis()) AppPreferences.getInstance().put("last_notification_time", System.currentTimeMillis())
} }
} }
\ No newline at end of file
package com.base.datarecovery.fcm;
import android.util.Log;
import com.base.datarecovery.MyApplication;
import java.util.Timer;
import java.util.TimerTask;
public class RecoveryTimerManager {
private static RecoveryTimerManager instance;
private Timer taskTimer;
private boolean isTimerActive;
private RecoveryTimerManager() {
// 将构造方法设置为私有,确保通过 getInstance 方法获取实例
}
public static synchronized RecoveryTimerManager getInstance() {
if (instance == null) {
instance = new RecoveryTimerManager();
}
return instance;
}
public void scheduleTask(long delay, long period) {
ensureTimerIsStopped(); // 确保在启动新定时任务前停止旧的定时器
taskTimer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
Log.d("glc", "Scheduled task is running");
if (ScreenStatusReceiver.isDeviceInteractive() && !ScreenStatusReceiver.isSecureLockActive() && MyApplication.PAUSED_VALUE!=1) {
Log.d("glc", "Scheduled task conditions are met");
// NotificationUtil.notifyUser(AppContext.getContext());
}
}
};
taskTimer.schedule(task, delay, period);
isTimerActive = true;
}
private void ensureTimerIsStopped() {
if (isTimerActive) {
taskTimer.cancel();
taskTimer = null;
isTimerActive = false;
}
}
public void stopTaskTimer() {
ensureTimerIsStopped();
// 清除所有取消的任务
if (taskTimer != null) {
taskTimer.purge();
}
}
public boolean isTaskTimerActive() {
return isTimerActive;
}
}
\ No newline at end of file
package com.base.datarecovery.fcm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import com.base.datarecovery.utils.AppPreferences;
public class ScreenStatusReceiver extends BroadcastReceiver {
private static boolean isDeviceInteractive = true;
private static boolean isSecureLockActive = false;
public static void setupScreenStatusListener(Context context) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_USER_PRESENT);
final Context applicationContext = context.getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
applicationContext.registerReceiver(new ScreenStatusReceiver(), intentFilter, Context.RECEIVER_EXPORTED);
} else {
applicationContext.registerReceiver(new ScreenStatusReceiver(), intentFilter);
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case Intent.ACTION_SCREEN_ON:
setDeviceInteractive(true);
break;
case Intent.ACTION_SCREEN_OFF:
setDeviceInteractive(false);
setSecureLockActive(true);
break;
case Intent.ACTION_USER_PRESENT:
setSecureLockActive(false);
if (isDeviceInteractive() && !isSecureLockActive()) {
int secureSetting = AppPreferences.getInstance().getInt("lockS", 1);
if (secureSetting == 1) {
// NotificationUtil.displayNotification(AppContext.getContext());
}
}
break;
}
}
private void setDeviceInteractive(boolean interactive) {
isDeviceInteractive = interactive;
}
public static boolean isDeviceInteractive() {
return isDeviceInteractive;
}
private void setSecureLockActive(boolean active) {
isSecureLockActive = active;
}
public static boolean isSecureLockActive() {
return isSecureLockActive;
}
}
\ No newline at end of file
package com.base.datarecovery.utils;
import android.content.Context;
import android.content.SharedPreferences;
import com.base.datarecovery.MyApplication;
public class AppPreferences {
private static AppPreferences sInstance;
private SharedPreferences sharedPreferences;
private static final String PREF_FILE_NAME = "app_prefs"; // 偏好文件名
private AppPreferences(Context context) {
sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
}
public static synchronized AppPreferences getInstance() {
if (sInstance == null) {
sInstance = new AppPreferences(MyApplication.context.getApplicationContext());
}
return sInstance;
}
// 通用 put 方法
public void put(String key, Object value) {
if (value instanceof Integer) {
sharedPreferences.edit().putInt(key, (Integer) value).apply();
} else if (value instanceof Long) {
sharedPreferences.edit().putLong(key, (Long) value).apply();
} else if (value instanceof Float) {
sharedPreferences.edit().putFloat(key, (Float) value).apply();
} else if (value instanceof Boolean) {
sharedPreferences.edit().putBoolean(key, (Boolean) value).apply();
} else if (value instanceof String) {
sharedPreferences.edit().putString(key, (String) value).apply();
} else {
throw new IllegalArgumentException("Unsupported type: " + value.getClass());
}
}
public void put(String key, Object value, boolean isCommit) {
SharedPreferences.Editor editor = sharedPreferences.edit();
if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value instanceof String) {
editor.putString(key, (String) value);
} else {
throw new IllegalArgumentException("Unsupported type: " + value.getClass());
}
// 根据 isCommit 参数的值决定使用 commit() 还是 apply()
if (isCommit) {
editor.commit();
} else {
editor.apply();
}
}
// 存入整数
public void putInt(String key, int value) {
sharedPreferences.edit().putInt(key, value).apply();
}
// 获取整数
public int getInt(String key, int defaultValue) {
return sharedPreferences.getInt(key, defaultValue);
}
// 存入长整数
public void putLong(String key, long value) {
sharedPreferences.edit().putLong(key, value).apply();
}
// 获取长整数
public long getLong(String key, long defaultValue) {
return sharedPreferences.getLong(key, defaultValue);
}
// 存入浮点数
public void putFloat(String key, float value) {
sharedPreferences.edit().putFloat(key, value).apply();
}
// 获取浮点数
public float getFloat(String key, float defaultValue) {
return sharedPreferences.getFloat(key, defaultValue);
}
// 存入布尔值
public void putBoolean(String key, boolean value) {
sharedPreferences.edit().putBoolean(key, value).apply();
}
// 获取布尔值
public boolean getBoolean(String key, boolean defaultValue) {
return sharedPreferences.getBoolean(key, defaultValue);
}
// 存入字符串
public void putString(String key, String value) {
sharedPreferences.edit().putString(key, value).apply();
}
// 获取字符串
public String getString(String key, String defaultValue) {
return sharedPreferences.getString(key, defaultValue);
}
// 检查某个键是否存在
public boolean contains(String key) {
return sharedPreferences.contains(key);
}
// 移除某个键
public void remove(String key) {
sharedPreferences.edit().remove(key).apply();
}
// 清除所有数据
public void clear() {
sharedPreferences.edit().clear().apply();
}
}
\ No newline at end of file
package com.base.datarecovery.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import com.base.datarecovery.help.BaseApplication;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@SuppressLint("ApplySharedPref")
public final class SPUtils {
private static final Map<String, SPUtils> SP_UTILS_MAP = new HashMap<>();
private SharedPreferences sp;
/**
* Return the single {@link SPUtils} instance
*
* @return the single {@link SPUtils} instance
*/
public static SPUtils getInstance() {
return getInstance("", Context.MODE_PRIVATE);
}
/**
* Return the single {@link SPUtils} instance
*
* @param mode Operating mode.
* @return the single {@link SPUtils} instance
*/
public static SPUtils getInstance(final int mode) {
return getInstance("", mode);
}
/**
* Return the single {@link SPUtils} instance
*
* @param spName The name of sp.
* @return the single {@link SPUtils} instance
*/
public static SPUtils getInstance(String spName) {
return getInstance(spName, Context.MODE_PRIVATE);
}
/**
* Return the single {@link SPUtils} instance
*
* @param spName The name of sp.
* @param mode Operating mode.
* @return the single {@link SPUtils} instance
*/
public static SPUtils getInstance(String spName, final int mode) {
if (isSpace(spName)) spName = "spUtils";
SPUtils spUtils = SP_UTILS_MAP.get(spName);
if (spUtils == null) {
synchronized (SPUtils.class) {
spUtils = SP_UTILS_MAP.get(spName);
if (spUtils == null) {
spUtils = new SPUtils(spName, mode);
SP_UTILS_MAP.put(spName, spUtils);
}
}
}
return spUtils;
}
private SPUtils(final String spName) {
sp = BaseApplication.context.getSharedPreferences(spName, Context.MODE_PRIVATE);
}
private SPUtils(final String spName, final int mode) {
sp = BaseApplication.context.getSharedPreferences(spName, mode);
}
/**
* Put the string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public void put(@NonNull final String key, final String value) {
put(key, value, false);
}
/**
* Put the string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void put(@NonNull final String key, final String value, final boolean isCommit) {
if (isCommit) {
sp.edit().putString(key, value).commit();
} else {
sp.edit().putString(key, value).apply();
}
}
/**
* Return the string value in sp.
*
* @param key The key of sp.
* @return the string value if sp exists or {@code ""} otherwise
*/
public String getString(@NonNull final String key) {
return getString(key, "");
}
/**
* Return the string value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the string value if sp exists or {@code defaultValue} otherwise
*/
public String getString(@NonNull final String key, final String defaultValue) {
return sp.getString(key, defaultValue);
}
/**
* Put the int value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public void put(@NonNull final String key, final int value) {
put(key, value, false);
}
/**
* Put the int value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void put(@NonNull final String key, final int value, final boolean isCommit) {
if (isCommit) {
sp.edit().putInt(key, value).commit();
} else {
sp.edit().putInt(key, value).apply();
}
}
/**
* Return the int value in sp.
*
* @param key The key of sp.
* @return the int value if sp exists or {@code -1} otherwise
*/
public int getInt(@NonNull final String key) {
return getInt(key, -1);
}
/**
* Return the int value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the int value if sp exists or {@code defaultValue} otherwise
*/
public int getInt(@NonNull final String key, final int defaultValue) {
return sp.getInt(key, defaultValue);
}
/**
* Put the long value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public void put(@NonNull final String key, final long value) {
put(key, value, false);
}
/**
* Put the long value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void put(@NonNull final String key, final long value, final boolean isCommit) {
if (isCommit) {
sp.edit().putLong(key, value).commit();
} else {
sp.edit().putLong(key, value).apply();
}
}
/**
* Return the long value in sp.
*
* @param key The key of sp.
* @return the long value if sp exists or {@code -1} otherwise
*/
public long getLong(@NonNull final String key) {
return getLong(key, -1L);
}
/**
* Return the long value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the long value if sp exists or {@code defaultValue} otherwise
*/
public long getLong(@NonNull final String key, final long defaultValue) {
return sp.getLong(key, defaultValue);
}
/**
* Put the float value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public void put(@NonNull final String key, final float value) {
put(key, value, false);
}
/**
* Put the float value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void put(@NonNull final String key, final float value, final boolean isCommit) {
if (isCommit) {
sp.edit().putFloat(key, value).commit();
} else {
sp.edit().putFloat(key, value).apply();
}
}
/**
* Return the float value in sp.
*
* @param key The key of sp.
* @return the float value if sp exists or {@code -1f} otherwise
*/
public float getFloat(@NonNull final String key) {
return getFloat(key, -1f);
}
/**
* Return the float value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the float value if sp exists or {@code defaultValue} otherwise
*/
public float getFloat(@NonNull final String key, final float defaultValue) {
return sp.getFloat(key, defaultValue);
}
/**
* Put the boolean value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public void put(@NonNull final String key, final boolean value) {
put(key, value, false);
}
/**
* Put the boolean value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void put(@NonNull final String key, final boolean value, final boolean isCommit) {
if (isCommit) {
sp.edit().putBoolean(key, value).commit();
} else {
sp.edit().putBoolean(key, value).apply();
}
}
/**
* Return the boolean value in sp.
*
* @param key The key of sp.
* @return the boolean value if sp exists or {@code false} otherwise
*/
public boolean getBoolean(@NonNull final String key) {
return getBoolean(key, false);
}
/**
* Return the boolean value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the boolean value if sp exists or {@code defaultValue} otherwise
*/
public boolean getBoolean(@NonNull final String key, final boolean defaultValue) {
return sp.getBoolean(key, defaultValue);
}
/**
* Put the set of string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public void put(@NonNull final String key, final Set<String> value) {
put(key, value, false);
}
/**
* Put the set of string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void put(@NonNull final String key,
final Set<String> value,
final boolean isCommit) {
if (isCommit) {
sp.edit().putStringSet(key, value).commit();
} else {
sp.edit().putStringSet(key, value).apply();
}
}
/**
* Return the set of string value in sp.
*
* @param key The key of sp.
* @return the set of string value if sp exists
* or {@code Collections.<String>emptySet()} otherwise
*/
public Set<String> getStringSet(@NonNull final String key) {
return getStringSet(key, Collections.<String>emptySet());
}
/**
* Return the set of string value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the set of string value if sp exists or {@code defaultValue} otherwise
*/
public Set<String> getStringSet(@NonNull final String key,
final Set<String> defaultValue) {
return sp.getStringSet(key, defaultValue);
}
/**
* Return all values in sp.
*
* @return all values in sp
*/
public Map<String, ?> getAll() {
return sp.getAll();
}
/**
* Return whether the sp contains the preference.
*
* @param key The key of sp.
* @return {@code true}: yes<br>{@code false}: no
*/
public boolean contains(@NonNull final String key) {
return sp.contains(key);
}
/**
* Remove the preference in sp.
*
* @param key The key of sp.
*/
public void remove(@NonNull final String key) {
remove(key, false);
}
/**
* Remove the preference in sp.
*
* @param key The key of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void remove(@NonNull final String key, final boolean isCommit) {
if (isCommit) {
sp.edit().remove(key).commit();
} else {
sp.edit().remove(key).apply();
}
}
/**
* Remove all preferences in sp.
*/
public void clear() {
clear(false);
}
/**
* Remove all preferences in sp.
*
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public void clear(final boolean isCommit) {
if (isCommit) {
sp.edit().clear().commit();
} else {
sp.edit().clear().apply();
}
}
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
}
...@@ -8,7 +8,7 @@ import android.net.Uri ...@@ -8,7 +8,7 @@ import android.net.Uri
import android.view.LayoutInflater import android.view.LayoutInflater
import com.base.datarecovery.R import com.base.datarecovery.R
import com.base.datarecovery.databinding.DialogRateStarBinding import com.base.datarecovery.databinding.DialogRateStarBinding
import com.base.datarecovery.utils.SPUtils import com.base.datarecovery.utils.AppPreferences
object RateStarPop { object RateStarPop {
...@@ -16,9 +16,9 @@ object RateStarPop { ...@@ -16,9 +16,9 @@ object RateStarPop {
fun Context.showRateStarPopDialog(mustShow: Boolean = false) { fun Context.showRateStarPopDialog(mustShow: Boolean = false) {
if (!mustShow) { if (!mustShow) {
val n = SPUtils.getInstance().getInt("RateNumbers", 0) val n = AppPreferences.getInstance().getInt("RateNumbers", 0)
SPUtils.getInstance().put("RateNumbers", n + 1) AppPreferences.getInstance().put("RateNumbers", n + 1)
if (SPUtils.getInstance().getBoolean("isRated", false)) { if (AppPreferences.getInstance().getBoolean("isRated", false)) {
return return
} }
if (n > 0 && n % 8 == 0) { if (n > 0 && n % 8 == 0) {
...@@ -56,7 +56,7 @@ object RateStarPop { ...@@ -56,7 +56,7 @@ object RateStarPop {
} }
binding.tvSubmit.setOnClickListener { binding.tvSubmit.setOnClickListener {
if (star >= 5) { if (star >= 5) {
SPUtils.getInstance().put("isRated", true) AppPreferences.getInstance().put("isRated", true)
try { try {
val uri = val uri =
Uri.parse("https://play.google.com/store/apps/details?id=" + this.packageName) Uri.parse("https://play.google.com/store/apps/details?id=" + this.packageName)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment