android - 有没有办法阻止我的应用在特定时间范围内发送通知?
问题描述
我正在尝试制作一个应用程序,当应用程序接收到的数据不应该是它应该是什么时通知用户(认为蒸汽低于 212 华氏度)。如果用户在应用程序中,应用程序还会显示信息。在这种情况下,我能够收到要发送的通知。唯一的问题是信息需要真正保持最新,因此每 10 秒更新一次。如果数据持续不正确,这会使应用程序每 10 秒发送一次通知。有没有办法防止在指定时间内重复通知?(约 10 - 15 分钟)
我曾尝试thread.sleep(1000)
在for
循环内使用以使其等待 10 分钟,但这会使整个更新系统暂停 10 分钟,因此不会向应用程序发送任何信息。我是 android studio 的新手,在网上找不到任何可以帮助我的东西。
这只是应用程序知道发送通知的方式。如果我可以继续使用它,那将是理想的,但如果有更好的方法,我愿意改变它。
//ERROR Notification
if (map.get("steamTemp") < 212 || map.get("steamTemp") > 500 ||
map.get("waterTemp") < 40 || map.get("waterTemp") > 150||
map.get("dieselFlow") < 50 || map.get("dieselFlow") > 100 ||
map.get("waterFlow") < 50 || map.get("waterFlow") > 100||
map.get("waterFeederLevel") < 10 || map.get("waterFeederLevel") > 150) {
NotificationManager notif = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification.Builder
(getApplicationContext())
.setContentTitle("ERROR: Device Error")
.setContentText("Please see app for more information.")
.setSmallIcon(R.drawable.error_notif)
.setSound(soundUri)
.build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
我希望在出现问题时发送通知,但在那之后等待 10 分钟再发送另一个通知。我上面解释的示例的问题thread.sleep(1000)
是它暂停了整个应用程序,而不仅仅是通知。这是不行的,因为如果用户查看应用程序,应用程序需要显示更新的信息。
解决方案
正如 carlosgub 提到的,您可以使用自己硬编码或用户输入的首选项来确定何时发送它们。这是一些示例代码:
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Date;
public class YourClass {
//Key in Shared Preferences to use
private static final String LAST_UPDATE = "lastUpdate";
//10 minutes, adjust to your preferences
private static final long NUMBER_MILLISECONDS_BETWEEN_UPDATES = (1000L * 60L * 10L);
//Your Shared Preferences name
private static final String SP_NAME = "yourSPName";
private static void saveLastUpdateTime(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
long x = new Date().getTime();
editor.putLong(LAST_UPDATE, x);
editor.commit();
}
private static long getLastUpdateTime(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sharedPref.getLong(LAST_UPDATE, -1);
}
public static boolean shouldSendNotification(Context context) {
long lastUpdate = getLastUpdateTime(context);
if (lastUpdate == -1) {
saveLastUpdateTime(context);
//This means it has yet to run
return true;
}
long now = new Date().getTime();
if ((now - lastUpdate) > NUMBER_MILLISECONDS_BETWEEN_UPDATES) {
saveLastUpdateTime(context);
return true;
} else {
return false;
}
}
}
在此处的代码中,您调用shouldSendNotification()
,如果它返回 false,则自上次运行以来尚未 10 分钟,如果返回 true,则自上次运行以来已超过 10 分钟(或从未运行过全部)。
要将它与您的代码一起使用,在构建notify
对象的方法的顶部,只需调用它,如果它返回 false,则返回:
if(!YourClass.shouldSendNotification(context)){
return;
}
只需确保根据您的喜好调整值(双关语)。