Java Code Examples for android.app.AlarmManager#set()

The following examples show how to use android.app.AlarmManager#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BootReceiver.java    From AssistantBySDK with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent mintent) {
	//if (Intent.ACTION_BOOT_COMPLETED.equals(mintent.getAction())) {  
           // 启动完成  
	Log.i("BootReceiver", "onReceive");
           Intent intent = new Intent(context, AlarmReceiver.class);  
           intent.setAction(AlarmReceiver.ACTION);  
           PendingIntent sender = PendingIntent.getBroadcast(context, 0,  
                   intent, 0);  
           AlarmManager am = (AlarmManager) context  
                   .getSystemService(Context.ALARM_SERVICE);  
           if(android.os.Build.VERSION.SDK_INT<android.os.Build.VERSION_CODES.KITKAT){
			/** 开机激活闹钟 **/
           	am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+60000, sender);
		}
		else{
			am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+60000, sender);
		}
      // }  
}
 
Example 2
Source File: StartNotificationReceiver.java    From al-muazzin with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void set(Context context, short timeIndex, Calendar actualTime) {
    if (Calendar.getInstance().after(actualTime)) {
        // Somehow current time is greater than the prayer time
        return;
    }

    Intent intent = new Intent(context, StartNotificationReceiver.class);
    intent.putExtra(CONSTANT.EXTRA_ACTUAL_TIME, actualTime.getTimeInMillis());
    intent.putExtra(CONSTANT.EXTRA_TIME_INDEX, timeIndex);

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        am.setExact(AlarmManager.RTC_WAKEUP, actualTime.getTimeInMillis(),
                PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
    } else {
        am.set(AlarmManager.RTC_WAKEUP, actualTime.getTimeInMillis(),
                PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
    }
}
 
Example 3
Source File: Reminder.java    From Expense-Tracker-App with MIT License 6 votes vote down vote up
public static void setReminder(Reminder reminder) {
    Calendar alarmCalendar = Calendar.getInstance();
    Calendar reminderDate = Calendar.getInstance();
    reminderDate.setTime(reminder.getDate());
    if (reminder.getDay() <= alarmCalendar.get(Calendar.DAY_OF_MONTH) || !DateUtils.isToday(reminder.getCreatedAt())) {
        alarmCalendar.setTime(DateUtils.getLastDateOfCurrentMonth());
    }
    alarmCalendar.set(Calendar.DATE, reminder.getDay());
    alarmCalendar.set(Calendar.HOUR_OF_DAY, reminderDate.get(Calendar.HOUR_OF_DAY));
    alarmCalendar.set(Calendar.MINUTE, reminderDate.get(Calendar.MINUTE));

    AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class);
    intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId());

    PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), alarmIntent);

}
 
Example 4
Source File: BaseFragment.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Set alarm for 2 minutes to clear the clipboard
 */
protected void setClearClipboardAlarm() {
    // create pending intent
    AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(getContext(), ClipboardAlarmReceiver.class);
    intent.setAction("co.banano.natriumwallet.alarm");
    PendingIntent alarmIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);

    // set a two minute alarm to start the pending intent
    if (alarmMgr != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120 * 1000, alarmIntent);
        } else {
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120 * 1000, alarmIntent);
        }
    }
}
 
Example 5
Source File: AlarmReceiver.java    From LibreAlarm with GNU General Public License v3.0 6 votes vote down vote up
public static void post(Context context) {
    long delay = Integer.valueOf(PreferencesUtil.getCheckGlucoseInterval(context)) * 60000 + 120000;
    Log.i(TAG, "set next check: " + delay + " (" + new SimpleDateFormat("HH:mm:ss")
            .format(new Date(delay + System.currentTimeMillis())) + ") "
            + new Exception().getStackTrace()[1]);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent intent = getAlarmReceiverIntent(context);
    alarmManager.cancel(intent);
    if (android.os.Build.VERSION.SDK_INT <= 18) {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + delay, intent);
    } else {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + delay, intent);
    }
    PreferenceManager.getDefaultSharedPreferences(context).edit()
            .putLong("next_check", System.currentTimeMillis() + delay).apply();
}
 
Example 6
Source File: ContextUtils.java    From kimai-android with MIT License 6 votes vote down vote up
/**
 * Restart the current app. Supply the class to start on startup
 */
public void restartApp(Class classToStart) {
    Intent inte = new Intent(_context, classToStart);
    PendingIntent inteP = PendingIntent.getActivity(_context, 555, inte, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
    if (_context instanceof Activity) {
        ((Activity) _context).finish();
    }
    if (mgr != null) {
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, inteP);
    } else {
        inte.addFlags(FLAG_ACTIVITY_NEW_TASK);
        _context.startActivity(inte);
    }
    Runtime.getRuntime().exit(0);
}
 
Example 7
Source File: PhonkServerService.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void uncaughtException(Thread thread, Throwable ex) {
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            Toast.makeText(PhonkServerService.this, "ooops!", Toast.LENGTH_LONG).show();
            Looper.loop();
        }
    }.start();
    //          handlerToast.post(runnable);

    AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mRestartPendingIntent);
    mNotificationManager.cancelAll();

    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(10);

    throw new RuntimeException(ex);
}
 
Example 8
Source File: DexCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
public void setRetryTimer() {
    if (CollectionServiceStarter.isBteWixelorWifiandBtWixel(getApplicationContext())
            || CollectionServiceStarter.isDexbridgeWixelorWifiandDexbridgeWixel(getApplicationContext())) {
        long retry_in;
        if(CollectionServiceStarter.isDexbridgeWixelorWifiandDexbridgeWixel(getApplicationContext())) {
            retry_in = (1000 * 25);
        }else {
            retry_in = (1000*65);
        }
        Log.d(TAG, "setRetryTimer: Restarting in: " + (retry_in / 1000) + " seconds");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        long wakeTime = calendar.getTimeInMillis() + retry_in;
        PendingIntent serviceIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
    }
}
 
Example 9
Source File: CrazyDailyCrashHandler.java    From CrazyDaily with Apache License 2.0 6 votes vote down vote up
/**
 * crash退出程序,0.5s后重启
 * 如果在系统onCreate前写的代码产生crash,需要特殊处理
 */
@Override
public void uncaughtException(Thread t, Throwable e) {
    PgyerCrashObservable.get().notifyObservers(t, e);
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    if (intent != null) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    PendingIntent restartIntent = PendingIntent.getActivity(
            context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (alarmManager != null) {
        alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent);
    }
    App.getInstance().abortedApp();
}
 
Example 10
Source File: MyReceiver.java    From BroadCastReceiver with Apache License 2.0 6 votes vote down vote up
public void setalarm(Context context, int time, int notiID) {

        //---use the AlarmManager to trigger an alarm---
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        //---get current date and time---
        Calendar calendar = Calendar.getInstance();
        //---sets the time for the alarm to trigger in 2 minutes from now---
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + time);
        calendar.set(Calendar.SECOND, 0);


        //---PendingIntent to launch receiver when the alarm triggers-
        //Intent notificationIntent = new Intent(getApplicationContext(), MyReceiver.class);
        Intent notificationIntent = new Intent(MainActivity.ACTION);
        notificationIntent.setPackage("edu.cs4730.broadcastboot"); //in API 26, it must be explicit now.
        notificationIntent.putExtra("notiid", notiID);
        PendingIntent contentIntent = PendingIntent.getBroadcast(context, notiID, notificationIntent, 0);
        Log.i(TAG, "Set alarm, I hope");
        //---sets the alarm to trigger---
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), contentIntent);

    }
 
Example 11
Source File: AndroidListenerIntents.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Issues a registration retry with delay. */
static void issueDelayedRegistrationIntent(Context context, AndroidClock clock,
    ByteString clientId, ObjectId objectId, boolean isRegister, int delayMs, int requestCode) {
  RegistrationCommand command = isRegister ?
      AndroidListenerProtos.newDelayedRegisterCommand(clientId, objectId) :
          AndroidListenerProtos.newDelayedUnregisterCommand(clientId, objectId);
  Intent intent = new Intent()
      .putExtra(EXTRA_REGISTRATION, command.toByteArray())
      .setClass(context, AlarmReceiver.class);

  // Create a pending intent that will cause the AlarmManager to fire the above intent.
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent,
      PendingIntent.FLAG_ONE_SHOT);

  // Schedule the pending intent after the appropriate delay.
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  long executeMs = clock.nowMs() + delayMs;
  alarmManager.set(AlarmManager.RTC, executeMs, pendingIntent);
}
 
Example 12
Source File: JoH.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static long wakeUpIntent(Context context, long delayMs, PendingIntent pendingIntent) {
    final long wakeTime = JoH.tsl() + delayMs;
    if (pendingIntent != null) {
        Log.d(TAG, "Scheduling wakeup intent: " + dateTimeText(wakeTime));
        final AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        try {
            alarm.cancel(pendingIntent);
        } catch (Exception e) {
            Log.e(TAG, "Exception cancelling alarm in wakeUpIntent: " + e);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (buggy_samsung) {
                alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, null), pendingIntent);
            } else {
                alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
    } else {
        Log.e(TAG, "wakeUpIntent - pending intent was null!");
    }
    return wakeTime;
}
 
Example 13
Source File: MissedReadingService.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
public void setAlarm(long alarmIn) {
    Calendar calendar = Calendar.getInstance();
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    long wakeTime = calendar.getTimeInMillis() + alarmIn;
    PendingIntent serviceIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
    } else
        alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
}
 
Example 14
Source File: ControlService.java    From deskcon-android with GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("NewApi")
@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
 }
 
Example 15
Source File: ExponentialBackoffScheduler.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Sets an alarm in the alarm manager.
 */
@VisibleForTesting
protected void setAlarm(AlarmManager am, long timestamp, PendingIntent retryPIntent) {
    Log.d(TAG, "now(" + new Date(getCurrentTime()) + ") refiringAt("
            + new Date(timestamp) + ")");
    try {
        am.set(AlarmManager.RTC, timestamp, retryPIntent);
    } catch (SecurityException e) {
        Log.e(TAG, "Failed to set backoff alarm.");
    }
}
 
Example 16
Source File: TimeTask.java    From TimeTask with Apache License 2.0 5 votes vote down vote up
/**
 * 装在定时任务
 * @param Time
 */
private void configureAlarmManager(long Time) {
    AlarmManager manager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
    PendingIntent pendIntent = getPendingIntent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Time, pendIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        manager.setExact(AlarmManager.RTC_WAKEUP, Time, pendIntent);
    } else {
        manager.set(AlarmManager.RTC_WAKEUP, Time, pendIntent);
    }
}
 
Example 17
Source File: AbstractWidgetProvider.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
protected void startServiceWithCheck(Context context, Intent intent) {
    try {
        context.startService(intent);
    } catch (IllegalStateException ise) {
        intent.putExtra("isInteractive", false);
        PendingIntent pendingIntent = PendingIntent.getService(context,
                0,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 10,
                pendingIntent);
    }
}
 
Example 18
Source File: MainActivity.java    From Favorite-Android-Client with Apache License 2.0 5 votes vote down vote up
/**
 * Restart the application.
 */
public void restartApplication() {
	Intent mStartActivity = new Intent(this, MainActivity.class);
	PendingIntent intent = PendingIntent.getActivity(this.getBaseContext(),
			0, mStartActivity, getIntent().getFlags());
	AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
	mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 300, intent);
	//System.exit(2);
	android.os.Process.killProcess(android.os.Process.myPid());
}
 
Example 19
Source File: AlarmHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
private static void createAlarm(Context context, IntervalTimer timer, PendingIntent pendingIntent) {
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (timer.getExecutionInterval() == -1) {
        // one time alarm
        alarmMgr.set(AlarmManager.RTC_WAKEUP, timer.getExecutionTime().getTimeInMillis(), pendingIntent);
    } else {
        // repeating alarm
        Calendar currentTime = Calendar.getInstance();
        Calendar exactExecutionTime = Calendar.getInstance();
        exactExecutionTime.set(Calendar.HOUR_OF_DAY, timer.getExecutionTime().get(Calendar.HOUR_OF_DAY));
        exactExecutionTime.set(Calendar.MINUTE, timer.getExecutionTime().get(Calendar.MINUTE));
        exactExecutionTime.set(Calendar.SECOND, 0);
        exactExecutionTime.set(Calendar.MILLISECOND, 0);

        while (exactExecutionTime.before(currentTime)) {
            exactExecutionTime.add(Calendar.MILLISECOND, (int) timer.getExecutionInterval());
        }

        if (Build.VERSION.SDK_INT >= 23) {
            alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, exactExecutionTime.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 23) {
            alarmMgr.setExact(AlarmManager.RTC_WAKEUP, exactExecutionTime.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT < 19) {
            alarmMgr.set(AlarmManager.RTC_WAKEUP, exactExecutionTime.getTimeInMillis(), pendingIntent);
        } else {
            Log.e("AlarmHandler", "Unknown SDK Version!");
        }
    }
}
 
Example 20
Source File: LoggerService.java    From android-logstash-logger with MIT License 4 votes vote down vote up
private void setCleanupWakeAlarm(long interval) {
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval,
            PendingIntent.getBroadcast(this, 0, new Intent(ACTION_CLEANUP), 0));
}