Уведомление о пожаре каждые 24 часа и в точное время 8 часов утра
Я использую AlarmManager()
для уведомления об увольнении и повторения его каждые 24 часа.
Мой код включен в onCreate()
в Splash Activity, который запускается первым, когда кто-либо открывает приложение. Пользователь может установить приложение в любое время. Поэтому я хочу, чтобы, когда пользователь устанавливает приложение, он проверяет время и затем запускает уведомление в 8 часов утра и повторяет его ежедневно. Я не хочу получать уведомления, когда кто-либо открывает приложение.
Мой код выглядит следующим образом:
public class Splash extends Activity {
final String WebsiteURL = "http://www.mytestbuddy.com";
String cookie;
@SuppressLint("SimpleDateFormat")
@Override
protected void onCreate(Bundle showSplash) {
// TODO Auto-generated method stub
super.onCreate(showSplash);
setContentView(R.layout.splash);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(
Splash.this, 0, myIntent, 0);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
CookieSyncManager.createInstance(this);
CookieManager cm = CookieManager.getInstance();
cm.setAcceptCookie(true);
CookieSyncManager.getInstance().sync();
if (cm.getCookie("" + WebsiteURL + "") != null) {
cookie = cm.getCookie("" + WebsiteURL + "").toString();
} else {
cookie = null;
}
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (cookie == null) {
Intent openStartingPoint = new Intent(
"com.MobileWeb.mytestbuddy.Login");
startActivity(openStartingPoint);
} else if (cookie.contains("Premium")) {
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
alarmManager.setRepeating(AlarmManager.RTC,
intendedTime, AlarmManager.INTERVAL_DAY,
pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC,
intendedTime, AlarmManager.INTERVAL_DAY,
pendingIntent);
}
Intent openStartingPoint = new Intent(
"com.MobileWeb.mytestbuddy.PremiumMain");
startActivity(openStartingPoint);
} else {
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
alarmManager.setRepeating(AlarmManager.RTC,
intendedTime, AlarmManager.INTERVAL_DAY,
pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC,
intendedTime, AlarmManager.INTERVAL_DAY,
pendingIntent);
}
Intent openStartingPoint = new Intent(
"com.MobileWeb.mytestbuddy.Main");
startActivity(openStartingPoint);
}
}
}
};
timer.start();
}
}
Ответы
Ответ 1
Сделайте так, как предложил chintan. Чтобы получить четкое изображение, exact solution
может выглядеть примерно так:
Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar firingCal= Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR, 8); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 0); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if(intendedTime >= currentTime){
// you can add buffer time too here to ignore some small differences in milliseconds
// set from today
alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else{
// set from next day
// you might consider using calendar.add() for adding one day to the current day
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
Ответ 2
Вот псевдокод:
Вы должны написать этот код внутри своего Splash.java
Шаг 1: Is_Alarm_Set();
[Boolean]
Шаг 2: false
[шаг 3]
Шаг 2: true
[шаг 8] (нет необходимости устанавливать)
Шаг 3: Get_Time()
[Текущее время мобильной связи]
Шаг 4: Find_Time_Difference()
[Эта функция найдет разницу между временем мобильного пользователя и временем исправления (8AM).]
Шаг 5: Теперь установите будильник в соответствии с разницей времени. [текущее время составляет 7 часов, а дата - 1-й день, а затем будильник 8 часов на следующий день.]
Шаг 6: Задайте дни повторения setRepeating()
Шаг 7: Будет срабатывать будильник в соответствии с вашим временем исправления 8 утра.
Шаг 8: Переключите свою деятельность.
Ответ 3
Ответ Appu мне очень помог, но если вы хотите, чтобы исправленная версия была немного более удобочитаемой и короткозахватной, посмотрите на это:
PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar firingCal= Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 8); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 0); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
if(firingCal.compareTo(currentCal) < 0) {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
}
Long intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC, intendedTime , AlarmManager.INTERVAL_DAY, pendingIntent);
Ответ 4
// Retrieve a PendingIntent that will perform a broadcast
Intent alarmIntent = new Intent(HomeContactActivity.this,
AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(
HomeContactActivity.this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at 10:00 AM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
manager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 86400000, // for repeating
// in every 24
// hours
pendingIntent);