我正在尝试制作一个应用程序,该应用程序将在用户收到的数据不应该是应有的数据时通知用户(认为蒸汽低于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)
示例的问题在于,它暂停了整个应用程序,而不仅仅是通知。这不行,因为如果用户查看该应用,则该应用需要显示更新的信息。
答案 0 :(得分:1)
正如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;
}
只需确保将值调整为您的首选项(Pun专用)。