我正在努力完成一项任务。这是正在发生的事情。我首先在第一个活动的字符串中保存共享首选项中的值,并将该值传递给下面的此活动。然后在我的第二个活动中,我称之为该值。然后我把android的当前时间转换为字符串。
=============================================== ==
@Lazy Ninja: 更新请检查: 好的。我得到的时间最终匹配!现在只是最后一件事,我如何继续运行这个" if statement"在后台,所以即使应用程序关闭,系统会继续检查这两个值吗?
=============================================== ==
更新代码:
Intent in = new Intent(Alarm.this, FajrAlarmRecieverActivity.class);
PendingIntent pi = PendingIntent.getActivity(Alarm.this, 2, in, PendingIntent.FLAG_CANCEL_CURRENT);
/*My Time from Shared Preference*/
//SharedPreferences prfs = getSharedPreferences("customeAlarmTimes", Context.MODE_PRIVATE);
//myTime = prfs.getString("Isha", "Isha");
String myTime = "11:15";
SimpleDateFormat formatter = new SimpleDateFormat("K:mm");
Date date = formatter.parse(myTime); // You will need try/catch around this
long millis = date.getTime();
/*My Time from Shared Preference*/
/*System Time*/
Date today = Calendar.getInstance().getTime();
String reportDate = new SimpleDateFormat("K:mm").format(today);
Date swag = formatter.parse(reportDate);
long currentTime= swag.getTime();
Log.d("SystemTime", reportDate);
Log.d("MyTime", myTime);
Log.d("SystemTime in Millis", currentTime+"");
Log.d("MyTime in Millis", millis+"");
if(millis == currentTime){
SendNotification();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, AlarmManager.INTERVAL_DAY, pi);
}
else if (millis > currentTime){
Toast mtoast = Toast.makeText(getApplicationContext(), "FAJR TIME > CURRENT TIME", Toast.LENGTH_LONG);
mtoast.show();
}
else if (millis < currentTime){
Toast mtoast = Toast.makeText(getApplicationContext(), "FAJR TIME < CURRENT TIME", Toast.LENGTH_LONG);
mtoast.show();
}
}
}
答案 0 :(得分:0)
使用重复闹钟。它将为您处理条件 请尝试以下
Intent i = new Intent(getApplicationContext(), FajrAlarmRecieverActivity.class);
PendingIntent sender = PendingIntent.getActivity(Alarm.this, 0, i, 0);
// Get Time from your sharedpreferences
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour); // set Fajr hour
calendar.set(Calendar.MINUTE, minute); // set Fajr minute
calendar.set(Calendar.SECOND, 0); // set seconds ( well no need for seconds)
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
别忘了在清单文件中添加FajrAlarmRecieverActivity
阅读完评论后,请使用set
警报触发后,从sharedPreferences中读取并再次设置警报。
编辑
获取当前时间
long currentTime= System.currentTimeMillis();
从您的sharedPrefs获取时间,并将其转换为毫秒
if( sharedTimeInMillis < currentTime ){
// your good stuff
}
将您的字符串时间转换为毫秒
myTime = prfs.getString("Isha", "Isha");
SimpleDateFormat formatter = new SimpleDateFormat("K:mm");
Date date = formatter.parse(myTime ); // You will need try/catch around this
long millis = date.getTime();