android.app.AlarmManager Java Examples

The following examples show how to use android.app.AlarmManager. 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: StringUtils.java    From FriendBook with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param calendar {@link Calendar}
 * @return 今天, 昨天, 前天, n天前
 */
public static String formatSomeDay(Calendar calendar) {
    if (calendar == null) return "?天前";
    Calendar mCurrentDate = Calendar.getInstance();
    long crim = mCurrentDate.getTimeInMillis(); // current
    long trim = calendar.getTimeInMillis(); // target
    long diff = crim - trim;

    int year = mCurrentDate.get(Calendar.YEAR);
    int month = mCurrentDate.get(Calendar.MONTH);
    int day = mCurrentDate.get(Calendar.DATE);

    mCurrentDate.set(year, month, day, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
        return "今天";
    }
    mCurrentDate.set(year, month, day - 1, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
        return "昨天";
    }
    mCurrentDate.set(year, month, day - 2, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
        return "前天";
    }
    return String.format("%s天前", diff / AlarmManager.INTERVAL_DAY);
}
 
Example #2
Source File: DexShareCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
public void setRetryTimer() {
    if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
        BgReading bgReading = BgReading.last();
        long retry_in;
        if (bgReading != null) {
            retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
        } else {
            retry_in = (1000 * 20);
        }
        Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (pendingIntent != null)
            alarm.cancel(pendingIntent);
        long wakeTime = calendar.getTimeInMillis() + retry_in;
        pendingIntent = 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, 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);
    }
}
 
Example #3
Source File: ContextUtils.java    From openlauncher with Apache License 2.0 6 votes vote down vote up
/**
 * Restart the current app. Supply the class to start on startup
 */
public void restartApp(Class classToStart) {
    Intent intent = new Intent(_context, classToStart);
    PendingIntent pendi = PendingIntent.getActivity(_context, 555, intent, 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, pendi);
    } else {
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        _context.startActivity(intent);
    }
    Runtime.getRuntime().exit(0);
}
 
Example #4
Source File: SensorStepServiceManager.java    From StepSensor with MIT License 6 votes vote down vote up
/**
 * Stops the {@link com.orangegangsters.github.lib.SensorStepService}
 */
public void stopAutoUpdateService(Context context) {
    Log.d(TAG, "Stopping StepSensorService after broadcast");
    AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    activateStepCounter(false);

    if (mService == null) {
        Intent retrieverIntent = new Intent(context, getReceiverClass());
        mService = PendingIntent.getBroadcast(context, SERVICE_ID, retrieverIntent, PendingIntent.FLAG_NO_CREATE);
    }
    if (mService != null) {
        alarm.cancel(mService);
        if (SensorStepService.getInstance() != null) {
            SensorStepService.getInstance().unregisterSensorStep();
        }
    }

    mService = null;
}
 
Example #5
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
public static void startDaily(Context context) {
    Intent alarmIntent = new Intent(context, BackgroundService.class);
    alarmIntent.setAction(BackgroundService.ACTION_DAILY);
    PendingIntent pi = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    long trigger = calendar.getTimeInMillis() + 24 * 3600 * 1000;

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pi);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, trigger, pi);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pi);
    Log.i(TAG, "Start daily job next=" + SimpleDateFormat.getDateTimeInstance().format(trigger));
}
 
Example #6
Source File: UrlConfigActivity.java    From freeiot-android with MIT License 6 votes vote down vote up
@Override
public void onBackPressed() {
	if (UserState.getInstances(this).isLogin()) {
		if (lastUrlState != UrlConfigManager.getCurrentState()) {
			UserState.getInstances(this).logout(this);
			setResult(RESULT_OK);
			
			Intent mStartActivity = new Intent(this, SplashActivity.class);
			int mPendingIntentId = 123456;
			PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
			mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
			MobclickAgent.onKillProcess(this);
			android.os.Process.killProcess(android.os.Process.myPid());
			return;
		}
	}
	ActivityUtils.animFinish(this, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
}
 
Example #7
Source File: PeriodicReplicationService.java    From sync-android with Apache License 2.0 6 votes vote down vote up
/** Stop replications currently in progress and cancel future scheduled replications. */
public synchronized void stopPeriodicReplication() {
    if (isPeriodicReplicationEnabled()) {
        setPeriodicReplicationEnabled(false);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, clazz);
        alarmIntent.setAction(PeriodicReplicationReceiver.ALARM_ACTION);
        PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        alarmManager.cancel(pendingAlarmIntent);

        stopReplications();
    } else {
        Log.i(TAG, "Attempted to stop an already stopped alarm manager");
    }
}
 
Example #8
Source File: EventPreferencesCalendar.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
private void removeAlarm(/*boolean startEvent, */Context context)
{
    try {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            //Intent intent = new Intent(context, EventCalendarBroadcastReceiver.class);
            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_EVENT_CALENDAR_BROADCAST_RECEIVER);
            //intent.setClass(context, EventCalendarBroadcastReceiver.class);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_NO_CREATE);
            if (pendingIntent != null) {
                //PPApplication.logE("EventPreferencesCalendar.removeAlarm", "alarm found");

                alarmManager.cancel(pendingIntent);
                pendingIntent.cancel();
            }
        }
    } catch (Exception e) {
        PPApplication.recordException(e);
    }
    PhoneProfilesService.cancelWork(ElapsedAlarmsWorker.ELAPSED_ALARMS_CALENDAR_SENSOR_TAG_WORK+"_" + (int) _event._id);
}
 
Example #9
Source File: AlarmSchedulerFlusherTest.java    From mapbox-events-android with MIT License 6 votes vote down vote up
@Test
public void checksAlarmRegistered() throws Exception {
  Context mockedContext = mock(Context.class);
  AlarmManager mockedAlarmManager = mock(AlarmManager.class);
  AlarmReceiver mockedAlarmReceiver = mock(AlarmReceiver.class);
  AlarmSchedulerFlusher theAlarmSchedulerFlusher = new AlarmSchedulerFlusher(mockedContext, mockedAlarmManager,
    mockedAlarmReceiver);

  theAlarmSchedulerFlusher.register();

  IntentFilter expectedFilter = new IntentFilter("com.mapbox.scheduler_flusher");
  verify(mockedContext, times(1)).registerReceiver(
    eq(mockedAlarmReceiver),
    refEq(expectedFilter)
  );
}
 
Example #10
Source File: LockSettingsStrongAuth.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void handleScheduleStrongAuthTimeout(int userId) {
    final DevicePolicyManager dpm =
            (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
    long when = SystemClock.elapsedRealtime() + dpm.getRequiredStrongAuthTimeout(null, userId);
    // cancel current alarm listener for the user (if there was one)
    StrongAuthTimeoutAlarmListener alarm = mStrongAuthTimeoutAlarmListenerForUser.get(userId);
    if (alarm != null) {
        mAlarmManager.cancel(alarm);
    } else {
        alarm = new StrongAuthTimeoutAlarmListener(userId);
        mStrongAuthTimeoutAlarmListenerForUser.put(userId, alarm);
    }
    // schedule a new alarm listener for the user
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, when, STRONG_AUTH_TIMEOUT_ALARM_TAG,
            alarm, mHandler);
}
 
Example #11
Source File: BleService.java    From beacons-android with Apache License 2.0 6 votes vote down vote up
private void initializeService() {
    if(D) Log.d(TAG, "initializeService");

    Beacons.initialize(this);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    IntentFilter localIntentFilter = new IntentFilter(ACTION_ITEM_STATE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, localIntentFilter);

    // Bluetooth events are not received when using LocalBroadcastManager
    IntentFilter systemIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver, systemIntentFilter);

    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    if (null != bluetoothManager) {
        mAdvertisersManager = new AdvertisersManager(bluetoothManager, this);

        restoreSavedState();
    }
}
 
Example #12
Source File: ScheduledUpdatesAlarmManager.java    From Mizuu with Apache License 2.0 6 votes vote down vote up
public static void startUpdate(int type, Context context, long when) {
	AlarmManager alarmMan = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

	if (type == MOVIES) {
		// We don't want multiple instances of the movie library service to run at the same time
		if (MizLib.isMovieLibraryBeingUpdated(context))
			return;
	} else {
		// We don't want multiple instances of the TV show library service to run at the same time
		if (MizLib.isTvShowLibraryBeingUpdated(context))
			return;
	}
	Intent defineIntent = new Intent(context, (type == MOVIES) ? MovieLibraryUpdate.class : TvShowsLibraryUpdate.class);
	defineIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	PendingIntent piWakeUp = PendingIntent.getService(context,0, defineIntent, PendingIntent.FLAG_UPDATE_CURRENT);

	if (when > -1) {
		alarmMan.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when, piWakeUp);
		
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = settings.edit();
		editor.putLong((type == MOVIES) ? NEXT_SCHEDULED_MOVIE_UPDATE : NEXT_SCHEDULED_TVSHOWS_UPDATE, System.currentTimeMillis() + when);
		editor.apply();
	}
}
 
Example #13
Source File: SmoothieApplicationModule.java    From toothpick with Apache License 2.0 6 votes vote down vote up
private void bindSystemServices(Application application) {
  bindSystemService(application, LocationManager.class, LOCATION_SERVICE);
  bindSystemService(application, WindowManager.class, WINDOW_SERVICE);
  bindSystemService(application, ActivityManager.class, ACTIVITY_SERVICE);
  bindSystemService(application, PowerManager.class, POWER_SERVICE);
  bindSystemService(application, AlarmManager.class, ALARM_SERVICE);
  bindSystemService(application, NotificationManager.class, NOTIFICATION_SERVICE);
  bindSystemService(application, KeyguardManager.class, KEYGUARD_SERVICE);
  bindSystemService(application, Vibrator.class, VIBRATOR_SERVICE);
  bindSystemService(application, ConnectivityManager.class, CONNECTIVITY_SERVICE);
  bindSystemService(application, WifiManager.class, WIFI_SERVICE);
  bindSystemService(application, InputMethodManager.class, INPUT_METHOD_SERVICE);
  bindSystemService(application, SearchManager.class, SEARCH_SERVICE);
  bindSystemService(application, SensorManager.class, SENSOR_SERVICE);
  bindSystemService(application, TelephonyManager.class, TELEPHONY_SERVICE);
  bindSystemService(application, AudioManager.class, AUDIO_SERVICE);
  bindSystemService(application, DownloadManager.class, DOWNLOAD_SERVICE);
  bindSystemService(application, ClipboardManager.class, CLIPBOARD_SERVICE);
}
 
Example #14
Source File: MissedReadingService.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
public void setAlarm(long alarmIn, boolean force) {
    if(!force && (alarmIn < 5 * 60 * 1000)) {
        // No need to check more than once every 5 minutes
        alarmIn = 5 * 60 * 1000;
    }
	Log.d(TAG, "Setting timer to  " + alarmIn / 60000 + " minutes from now" );
    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 #15
Source File: Alarms.java    From MuslimMateAndroid with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Function to set alarm notification every day
 *
 * @param context Application context
 * @param hour    Hour of alarm
 * @param min     Min of alarm
 * @param id      ID of alarm
 */
public static void setAlarmForAzkar(Context context, int hour, int min, int id , String type) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, min);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Bundle details = new Bundle();
    details.putString("Azkar", type);
    Intent alarmReceiver = new Intent(context, AzkarAlarm.class);
    alarmReceiver.putExtras(details);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, alarmReceiver, PendingIntent.FLAG_UPDATE_CURRENT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // kitkat...
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    } else {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
    }
}
 
Example #16
Source File: LogRunnerReceiver.java    From callmeter with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Schedule next update.
 *
 * @param context {@link Context}
 * @param delay   delay in milliseconds
 * @param action  {@link Intent}'s action
 */
public static void schedNext(final Context context, final long delay, final String action) {
    Log.d(TAG, "schedNext(ctx, ", delay, ",", action, ")");
    final Intent i = new Intent(context, LogRunnerReceiver.class);
    if (action != null) {
        i.setAction(action);
    }
    try {
        final PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        final long t = SystemClock.elapsedRealtime() + delay;
        final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.ELAPSED_REALTIME, t, pi);
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, "schedule next check failed", e);
    }
}
 
Example #17
Source File: EventPreferencesSMS.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
@SuppressLint({"SimpleDateFormat", "NewApi"})
private void setAlarm(long alarmTime, Context context)
{
    if (!_permanentRun) {
        if (_startTime > 0) {
            /*if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("EventPreferencesSMS.setAlarm", "endTime=" + result);
            }*/

            /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
                //Intent intent = new Intent(context, SMSEventEndBroadcastReceiver.class);
                Intent intent = new Intent();
                intent.setAction(PhoneProfilesService.ACTION_SMS_EVENT_END_BROADCAST_RECEIVER);
                //intent.setClass(context, SMSEventEndBroadcastReceiver.class);

                //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                if (alarmManager != null) {
                    Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
                    editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime + Event.EVENT_ALARM_TIME_SOFT_OFFSET, infoPendingIntent);
                    alarmManager.setAlarmClock(clockInfo, pendingIntent);
                }
            } else {
                Calendar now = Calendar.getInstance();
                long elapsedTime = (alarmTime + Event.EVENT_ALARM_TIME_OFFSET) - now.getTimeInMillis();

                if (PPApplication.logEnabled()) {
                    long allSeconds = elapsedTime / 1000;
                    long hours = allSeconds / 60 / 60;
                    long minutes = (allSeconds - (hours * 60 * 60)) / 60;
                    long seconds = allSeconds % 60;

                    PPApplication.logE("EventPreferencesSMS.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
                }

                Data workData = new Data.Builder()
                        .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_SMS_EVENT_END_SENSOR)
                        .build();

                OneTimeWorkRequest worker =
                        new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                                .addTag("elapsedAlarmsSMSSensorWork_"+(int)_event._id)
                                .setInputData(workData)
                                .setInitialDelay(elapsedTime, TimeUnit.MILLISECONDS)
                                .build();
                try {
                    WorkManager workManager = WorkManager.getInstance(context);
                    PPApplication.logE("[HANDLER] EventPreferencesSMS.setAlarm", "enqueueUniqueWork - elapsedTime="+elapsedTime);
                    //workManager.enqueueUniqueWork("elapsedAlarmsSMSSensorWork_"+(int)_event._id, ExistingWorkPolicy.KEEP, worker);
                    workManager.enqueue(worker);
                } catch (Exception ignored) {}
            }*/

            //Intent intent = new Intent(context, SMSEventEndBroadcastReceiver.class);
            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_SMS_EVENT_END_BROADCAST_RECEIVER);
            //intent.setClass(context, SMSEventEndBroadcastReceiver.class);

            //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null) {
                if (ApplicationPreferences.applicationUseAlarmClock) {
                    Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
                    editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime + Event.EVENT_ALARM_TIME_SOFT_OFFSET, infoPendingIntent);
                    alarmManager.setAlarmClock(clockInfo, pendingIntent);
                }
                else {
                    //if (android.os.Build.VERSION.SDK_INT >= 23)
                        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else //if (android.os.Build.VERSION.SDK_INT >= 19)
                    //    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else
                    //    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                }
            }
        }
    }
}
 
Example #18
Source File: EditNoteActivity.java    From Jide-Note with MIT License 6 votes vote down vote up
/**
 * 开启一个闹钟
 */
private void setAlarmReceiver(String year,String month,String day,String hour,String minute ){

    Intent receiverIntent = new Intent(getApplicationContext(), NoteAlarmReceiver.class);
    long dbId = note.getId();
    LogUtils.e(TAG,"dbId ==> "+dbId);

    receiverIntent.putExtra(BaseNote.KEY_DB_ID,dbId );

    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), note.getAlarmReqCode(), receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day), Integer.parseInt(hour), Integer.parseInt(minute));
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    LogUtils.e("YEAR MONTH DAY "+calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+"-"+calendar.get(Calendar.DAY_OF_MONTH));
    LogUtils.e("HOUR MINUTE "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE));

    long time = calendar.getTimeInMillis();
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
 
Example #19
Source File: Alarm.java    From AnotherRSS with The Unlicense 5 votes vote down vote up
public void retry(Context context, long sec) {
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, Alarm.class);
    pref.edit().putBoolean("isRetry", true).apply();
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + sec * 1000L, pi);
}
 
Example #20
Source File: RedPacketPollingService.java    From letv with Apache License 2.0 5 votes vote down vote up
public static void startPollingService(Context context, int minute) {
    if (context != null) {
        PendingIntent pending = PendingIntent.getService(context, 1521045111, new Intent(context, RedPacketPollingService.class), 268435456);
        AlarmManager alarm = (AlarmManager) context.getSystemService(NotificationCompat.CATEGORY_ALARM);
        alarm.cancel(pending);
        alarm.set(2, SystemClock.elapsedRealtime() + ((long) ((minute * 60) * 1000)), pending);
    }
}
 
Example #21
Source File: BedtimeNotificationHelper.java    From GotoSleep with GNU General Public License v3.0 5 votes vote down vote up
private void setBedtimeNotification(Context context, Calendar bedtime){
    Intent intent1 = new Intent(context, BedtimeNotificationReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
            FIRST_NOTIFICATION_ALARM_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, bedtime.getTimeInMillis(), pendingIntent);
    } else {
        am.setExact(AlarmManager.RTC_WAKEUP, bedtime.getTimeInMillis(), pendingIntent);
    }


}
 
Example #22
Source File: BaseSCActivity.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private void d()
{
    AlarmManager alarmmanager = (AlarmManager)getSystemService("alarm");
    Intent intent = new Intent();
    intent.setAction("com.xiaomi.hm.health.set_max_latency");
    alarmmanager.cancel(PendingIntent.getBroadcast(this, 0, intent, 0));
}
 
Example #23
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static void stopWeatherUpdates(Context context) {
    Intent alarmIntent = new Intent(context, BackgroundService.class);
    alarmIntent.setAction(BackgroundService.ACTION_UPDATE_WEATHER);
    PendingIntent pi = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pi);
    Log.i(TAG, "Stop weather updates");

    removeWeatherNotification(context);
    removeRainNotification(context);
}
 
Example #24
Source File: RootApplication.java    From Android_framework with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void uncaughtException(Thread thread, Throwable ex) {
    //启动首页
    Intent intent = new Intent();
    intent.setAction("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.LAUNCHER");
    intent.addCategory("com.android.framework.MAINPAGE");
    PendingIntent restartIntent = PendingIntent.getActivity(getInstance(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    //退出程序
    AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);

    ActivityManager.getInstance().finishAllActivityWithoutClose();
}
 
Example #25
Source File: DistanceFilterLocationProvider.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

    // Stop-detection PI
    stationaryAlarmPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_ALARM_ACTION), 0);
    registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION));

    // Stationary region PI
    stationaryRegionPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_REGION_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
    registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION));

    // Stationary location monitor PI
    stationaryLocationPollingPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0);
    registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION));

    // One-shot PI (TODO currently unused)
    singleUpdatePI = PendingIntent.getBroadcast(mContext, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
    registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));

    // Location criteria
    criteria = new Criteria();
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(true);
    criteria.setCostAllowed(true);
}
 
Example #26
Source File: AlarmHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Cancels an existing Alarm
 *
 * @param context any suitable context
 * @param timer   Timer that this alarm would activate
 */

public static void cancelAlarm(Context context, Timer timer) {
    Log.d("AlarmHandler", "cancelling alarm of timer: " + timer.getId());
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, createAlarmIntent(timer), PendingIntent.FLAG_UPDATE_CURRENT);

    Log.d("AlarmHandler", "intent: " + createAlarmIntent(timer));
    Log.d("AlarmHandler", "time: " + timer.getExecutionTime().getTime().toLocaleString());
    alarmMgr.cancel(pendingIntent);
}
 
Example #27
Source File: LocalBackupManager.java    From narrate-android with Apache License 2.0 5 votes vote down vote up
private static void enableBackup() {
    Intent intent = new Intent("NARRATE_BACKUP");
    intent.setClass(GlobalApplication.getAppContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(GlobalApplication.getAppContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) GlobalApplication.getAppContext().getSystemService(GlobalApplication.getAppContext().ALARM_SERVICE);

    int interval = Settings.getLocalBackupFrequency();

    if ( interval > -1 ) {
        long millis = 0;

        switch (interval) {
            case 0:
                millis = DateUtil.DAY_IN_MILLISECONDS;
                break;
            case 1:
                millis = DateUtil.WEEK_IN_MILLISECONDS;
                break;
            case 2:
                millis = DateUtil.WEEK_IN_MILLISECONDS * 4;
                break;
        }

        // delay things by a second
        am.setRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + (30 * DateUtil.SECOND_IN_MILLISECONDS), millis, pendingIntent);
    }
}
 
Example #28
Source File: Notifications.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void ArmTimer(Context ctx, boolean unclearAlert) {
    Calendar calendar = Calendar.getInstance();
    final long now = calendar.getTimeInMillis();
    Log.d("Notifications", "ArmTimer called");

    long wakeTime = calcuatleArmTime(ctx, now, unclearAlert);

    
    if(wakeTime < now ) {
        Log.e("Notifications" , "ArmTimer recieved a negative time, will fire in 6 minutes");
        wakeTime = now + 6 * 60000;
    } else if  (wakeTime >=  now + 6 * 60000) {
    	 Log.i("Notifications" , "ArmTimer recieved a bigger time, will fire in 6 minutes");
         wakeTime = now + 6 * 60000;
    }  else if (wakeTime == now) {
        Log.e("Notifications", "should arm right now, waiting one more second to avoid infinitue loop");
        wakeTime = now + 1000;
    }
    
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);

    
    Log.d("Notifications" , "ArmTimer waking at: "+ new Date(wakeTime ) +" in " +
        (wakeTime - now) /60000d + " minutes");
    if (wakeIntent != null)
        alarm.cancel(wakeIntent);
    wakeIntent = 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, wakeIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
    } else {
        alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
    }
}
 
Example #29
Source File: WidgetProviderTest.java    From materialistic with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Before
public void setUp() {
    widgetProvider = new WidgetProvider();
    alarmManager = (AlarmManager) RuntimeEnvironment.application.getSystemService(Context.ALARM_SERVICE);
    jobScheduler = (JobScheduler) RuntimeEnvironment.application.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    widgetManager = AppWidgetManager.getInstance(RuntimeEnvironment.application);
    appWidgetId = shadowOf(widgetManager).createWidget(WidgetProvider.class, R.layout.appwidget);
}
 
Example #30
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ping track
 */
private void pingIni() {
       AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
       Intent i = new Intent(this, LocAlarmService.class);
       i.setAction(Util.INTENT_ACTION_PING_INI);
       PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
       am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
               Util.INTERVAL_PING, pi);		
}