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

The following examples show how to use android.app.AlarmManager#setInexactRepeating() . 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 Yamba with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

	SharedPreferences prefs = PreferenceManager
			.getDefaultSharedPreferences(context);
	long interval = Long.parseLong(prefs.getString("interval",
			Long.toString(DEFAULT_INTERVAL)));

	PendingIntent operation = PendingIntent.getService(context, -1,
			new Intent(context, RefreshService.class),
			PendingIntent.FLAG_UPDATE_CURRENT);

	AlarmManager alarmManager = (AlarmManager) context
			.getSystemService(Context.ALARM_SERVICE);

	if (interval == 0) {
		alarmManager.cancel(operation);
		Log.d(TAG, "cancelling repeat operation");
	} else {
		alarmManager.setInexactRepeating(AlarmManager.RTC,
				System.currentTimeMillis(), interval, operation);
		Log.d(TAG, "setting repeat operation for: " + interval);
	}
	Log.d(TAG, "onReceived");
}
 
Example 2
Source File: SyncManager.java    From LibreNews-Android with GNU General Public License v3.0 6 votes vote down vote up
public void startSyncService(){
    Intent intent = new Intent(context, RefreshBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 11719, intent, 0);
    String val = prefs.getString("refresh_preference", "60");
    int syncRaw = Integer.valueOf(val);
    long syncInterval = syncRaw*60000; // milliseconds
    AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.cancel(pendingIntent); // to ensure we don't have two sync daemons running
    if(!prefs.getBoolean("automatically_refresh", true)){
        sendDebugNotification("Sync service not enabled (would have been @ " + syncInterval + ")", context);
        return;
        // don't sync if they have disabled syncs!
    }
    alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + syncInterval,
            syncInterval, pendingIntent);
    sendDebugNotification("Sync service started at an interval of " + syncInterval, context);
}
 
Example 3
Source File: AppListener.java    From glimmr with Apache License 2.0 6 votes vote down vote up
@Override
public void scheduleAlarms(AlarmManager mgr, PendingIntent pendingIntent,
        Context context) {
    /* If notifications off, ensure alarms are cancelled and return */
    SharedPreferences prefs =
        PreferenceManager.getDefaultSharedPreferences(context);
    boolean enableNotifications =
        prefs.getBoolean(Constants.KEY_ENABLE_NOTIFICATIONS, false);
    if (!enableNotifications) {
        if (BuildConfig.DEBUG) Log.d(TAG, "Cancelling alarms");
        AppService.cancelAlarms(context);
        return;
    }

    mMinutes = getMinutes(context);
    mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime()+mMinutes*60*1000,
            mMinutes*60*1000, pendingIntent);
    if (BuildConfig.DEBUG) {
        Log.d(TAG, String.format("Set alarms for %d minute intervals",
                mMinutes));
    }
}
 
Example 4
Source File: AlarmSetter.java    From three-things-today with Apache License 2.0 6 votes vote down vote up
public static void setDailyAlarm(Context context) {
    Intent notifyIntent = new Intent(context, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context, 0, notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    // TODO(smcgruer): Allow user to configure the time.
    final Calendar cal = Calendar.getInstance();
    if (cal.get(Calendar.HOUR_OF_DAY) >= 20)
        cal.add(Calendar.DATE, 1);
    cal.set(Calendar.HOUR_OF_DAY, 20);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent);
}
 
Example 5
Source File: AlarmReceiver.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
private static void scheduleCleanups (final Context context, final AlarmManager am) {
	final PendingIntent i = PendingIntent.getBroadcast(context, NotificationIds.BASE_ALARM_ID + ACTION_CLEANUP,
			new Intent(context, AlarmReceiver.class).putExtra(KEY_ACTION, ACTION_CLEANUP),
			PendingIntent.FLAG_CANCEL_CURRENT);
	am.cancel(i);
	am.setInexactRepeating(
			AlarmManager.ELAPSED_REALTIME,
			SystemClock.elapsedRealtime(),
			AlarmManager.INTERVAL_DAY,
			i);
}
 
Example 6
Source File: AlarmHandler.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
private void setRepeatingAlarm(Context context, int dayOfWeek, Calendar nextAlarmTimestamp)
{
    Timber.d("Set repeating alarm for %s", nextAlarmTimestamp.getTime());
    PendingIntent alarmPendingIntent = getPendingAlarmIntent(context, dayOfWeek);
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, nextAlarmTimestamp.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY * 7, alarmPendingIntent);
}
 
Example 7
Source File: BootCompleteReceiver.java    From android-tv-leanback with Apache License 2.0 5 votes vote down vote up
private void scheduleRecommendationUpdate(Context context) {

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent recommendationIntent = new Intent(context, RecommendationsService.class);
        PendingIntent alarmIntent = PendingIntent.getService(context, 0, recommendationIntent, 0);

        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                INITIAL_DELAY,
                AlarmManager.INTERVAL_HALF_HOUR,
                alarmIntent);
    }
 
Example 8
Source File: IMHeartBeatManager.java    From sctalk with Apache License 2.0 5 votes vote down vote up
private void scheduleHeartbeat(int seconds){
    logger.d("heartbeat#scheduleHeartbeat every %d seconds", seconds);
    if (pendingIntent == null) {
        logger.w("heartbeat#fill in pendingintent");
        Intent intent = new Intent(ACTION_SENDING_HEARTBEAT);
        pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, 0);
        if (pendingIntent == null) {
            logger.w("heartbeat#scheduleHeartbeat#pi is null");
            return;
        }
    }

    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + seconds, seconds, pendingIntent);
}
 
Example 9
Source File: BlockchainService.java    From bither-android with Apache License 2.0 5 votes vote down vote up
private void scheduleStartBlockchainService(@Nonnull final Context context) {
    BitherSetting.SyncInterval syncInterval = AppSharedPreference.getInstance().getSyncInterval();
    if (syncInterval == BitherSetting.SyncInterval.OnlyOpenApp ||
            AddressManager.getInstance().getAllAddresses().size() == 0) {
        return;
    }
    long interval = AlarmManager.INTERVAL_HOUR;
    if (syncInterval == BitherSetting.SyncInterval.Normal) {
        final long lastUsedAgo = AppSharedPreference.getInstance().getLastUsedAgo();
        if (lastUsedAgo < BitherSetting.LAST_USAGE_THRESHOLD_JUST_MS) {
            interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            log.info("start INTERVAL_FIFTEEN_MINUTES");
        } else if (lastUsedAgo < BitherSetting.LAST_USAGE_THRESHOLD_RECENTLY_MS) {
            interval = AlarmManager.INTERVAL_HALF_DAY;
            log.info("start INTERVAL_HALF_DAY");
        } else {
            interval = AlarmManager.INTERVAL_DAY;
            log.info("start INTERVAL_DAY");
        }
    }
    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context
            .ALARM_SERVICE);
    final PendingIntent alarmIntent = PendingIntent.getService(context, 0,
            new Intent(context, BlockchainService.class), 0);
    alarmManager.cancel(alarmIntent);
    final long now = System.currentTimeMillis();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    // as of KitKat, set() is inexact
    {
        alarmManager.set(AlarmManager.RTC_WAKEUP, now + interval, alarmIntent);
    } else
    // workaround for no inexact set() before KitKat
    {
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now + interval,
                AlarmManager.INTERVAL_HOUR, alarmIntent);
    }
}
 
Example 10
Source File: PullingContentService.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
public void setAlarm(AlarmManager am, Context context, String action, long time) {
  Intent intent = new Intent(context, PullingContentService.class);
  intent.setAction(action);
  PendingIntent pendingIntent =
      PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, getElapsedRealtimeTrigger(time),
      getElapsedRealtimeTrigger(time), pendingIntent);
}
 
Example 11
Source File: AlarmScheduler.java    From bitseal with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Schedules an alarm.
 */
public void scheduleAlarms(AlarmManager manager, PendingIntent intent, Context context)
{
	Log.d(TAG, "Scheduling a restart of the BackgroundService in roughly " + TimeUtils.getTimeMessage(BACKGROUND_SERVICE_NORMAL_START_INTERVAL));		
	
	// Create an intent that will be used to restart the BackgroundService
	Intent baseIntent = new Intent(context, BackgroundService.class);
	baseIntent.putExtra(BackgroundService.PERIODIC_BACKGROUND_PROCESSING_REQUEST, BackgroundService.BACKGROUND_PROCESSING_REQUEST);
	PendingIntent pendingIntent = PendingIntent.getService(context, 0, baseIntent, PendingIntent.FLAG_CANCEL_CURRENT);
	
	// Schedule a repeating alarm for restarting the BackgroundService
	long restartIntervalMilliseconds = BACKGROUND_SERVICE_NORMAL_START_INTERVAL * 1000;
	manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + restartIntervalMilliseconds, restartIntervalMilliseconds, pendingIntent);
}
 
Example 12
Source File: NotificationService.java    From Weather with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onHandleWork(@NonNull Intent intent) {
    CheckConnection checkNetwork = new CheckConnection(this);
    if (!checkNetwork.isNetworkAvailable()) {
        return;
    }

    Log.i("In" , "Notification Service Alarm");
    intent = NotificationService.newIntent(this);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    prefs = new Prefs(this);
    long intervalMillis = Long.parseLong(prefs.getTime());
    if (alarmManager != null)
        if (new Prefs(this).getNotifs()) {
            alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime(),
                    intervalMillis,
                    pendingIntent);
        } else {
            alarmManager.cancel(pendingIntent);
            pendingIntent.cancel();
        }

    String city = prefs.getCity();
    String units = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PREF_TEMPERATURE_UNITS , Constants.METRIC);

    try {
        WeatherInfo weather;
        weather = new Request(this).getItems(city, units);
        if (new Prefs(this).getNotifs())
            weatherNotification(weather);
    } catch (IOException e) {
        Log.e(TAG, "Error get weather", e);
    }
}
 
Example 13
Source File: NotificationScheduler.java    From Muslim-Athkar-Islamic-Reminders with MIT License 5 votes vote down vote up
public static void setReminder(Context context,Class<?> cls,int hour, int min, long interval)
    {
        Calendar calendar = Calendar.getInstance();

        Calendar setCalendar = Calendar.getInstance();
        setCalendar.set(Calendar.HOUR_OF_DAY, hour);
        setCalendar.set(Calendar.MINUTE, min);
        setCalendar.set(Calendar.SECOND, 0);

//         cancel already scheduled reminders
        cancelReminder(context,cls);

        if(setCalendar.before(calendar))
            setCalendar.add(Calendar.MILLISECOND, (int) interval);

        // Enable a receiver
        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);


        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setCalendar.getTimeInMillis(), interval, pendingIntent);

    }
 
Example 14
Source File: BlockedDomainAlarmHelper.java    From notSABS with MIT License 5 votes vote down vote up
public static void scheduleAlarm() {
    Intent intent = new Intent(App.get().getApplicationContext(), BlockedDomainAlarmReceiver.class);
    Log.d(TAG, "Alarm not set. Setting alarm");
    final PendingIntent pIntent = PendingIntent.getBroadcast(App.get().getApplicationContext(), REQUEST_CODE,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);
    long firstMillis = System.currentTimeMillis();
    AlarmManager alarm = (AlarmManager) App.get().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
            AlarmManager.INTERVAL_HOUR, pIntent);
}
 
Example 15
Source File: AlarmReceiver.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
private static void scheduleUpdates (final Context context, final AlarmManager am) {
	final PendingIntent i = PendingIntent.getBroadcast(context, NotificationIds.BASE_ALARM_ID + ACTION_UPDATE,
			new Intent(context, AlarmReceiver.class).putExtra(KEY_ACTION, ACTION_UPDATE),
			PendingIntent.FLAG_CANCEL_CURRENT);
	am.cancel(i);
	am.setInexactRepeating(
			AlarmManager.ELAPSED_REALTIME_WAKEUP,
			SystemClock.elapsedRealtime(),
			AlarmManager.INTERVAL_FIFTEEN_MINUTES,
			i);
}
 
Example 16
Source File: UpdateService.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Schedule this service to update the app index while canceling any previously
 * scheduled updates, according to the current preferences. Should be called
 * a) at boot, b) if the preference is changed, or c) on startup, in case we get
 * upgraded. It works differently on {@code android-21} and newer, versus older,
 * due to the {@link JobScheduler} API handling it very nicely for us.
 *
 * @see <a href="https://developer.android.com/about/versions/android-5.0.html#Power">Project Volta: Scheduling jobs</a>
 */
public static void schedule(Context context) {
    Preferences prefs = Preferences.get();
    long interval = prefs.getUpdateInterval();
    int data = prefs.getOverData();
    int wifi = prefs.getOverWifi();
    boolean scheduleNewJob =
            interval != Preferences.UPDATE_INTERVAL_DISABLED
                    && !(data == Preferences.OVER_NETWORK_NEVER && wifi == Preferences.OVER_NETWORK_NEVER);

    if (Build.VERSION.SDK_INT < 21) {
        Intent intent = new Intent(context, UpdateService.class);
        PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);

        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pending);
        if (scheduleNewJob) {
            alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                    SystemClock.elapsedRealtime() + 5000, interval, pending);
            Utils.debugLog(TAG, "Update scheduler alarm set");
        } else {
            Utils.debugLog(TAG, "Update scheduler alarm not set");
        }
    } else {
        Utils.debugLog(TAG, "Using android-21 JobScheduler for updates");
        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName = new ComponentName(context, UpdateJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName)
                .setRequiresDeviceIdle(true)
                .setPeriodic(interval);
        if (Build.VERSION.SDK_INT >= 26) {
            builder.setRequiresBatteryNotLow(true)
                    .setRequiresStorageNotLow(true);
        }
        if (data == Preferences.OVER_NETWORK_ALWAYS && wifi == Preferences.OVER_NETWORK_ALWAYS) {
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        } else {
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
        }

        jobScheduler.cancel(JOB_ID);
        if (scheduleNewJob) {
            jobScheduler.schedule(builder.build());
            Utils.debugLog(TAG, "Update scheduler alarm set");
        } else {
            Utils.debugLog(TAG, "Update scheduler alarm not set");
        }
    }
}
 
Example 17
Source File: Utility.java    From BlackLight with GNU General Public License v3.0 4 votes vote down vote up
public static void startServiceAlarm(Context context, Class<?> service, long interval) {
	AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	Intent i = new Intent(context, service);
	PendingIntent p = PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);
	am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, p);
}
 
Example 18
Source File: TickmateNotificationBroadcastReceiver.java    From tickmate with GNU General Public License v3.0 4 votes vote down vote up
public static void updateAlarm(Context context)
{
    Calendar cal = Calendar.getInstance();
    java.text.DateFormat timeFmt = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT);

    Boolean enabled = PreferenceManager.getDefaultSharedPreferences(context)
            .getBoolean("notification-enabled", false);

    String timeString = PreferenceManager.getDefaultSharedPreferences(context)
            .getString("notification-time", "");

    try {
        cal.setTime(timeFmt.parse(timeString));
    } catch (ParseException e) {
        Log.w(TAG, "Error parsing time: " + timeString);
        enabled = false;
    }

    Log.d(TAG, "Updating alarm; enabled=" + enabled.toString() + ", time=" + timeString);

    AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    Intent intent = new Intent(context, TickmateNotificationBroadcastReceiver.class);
    intent.putExtra("onetime", Boolean.FALSE);
    intent.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    // cancel any previous alarms
    am.cancel(pi);

    if (enabled) {

        Calendar alarmTime = Calendar.getInstance();
        alarmTime.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
        alarmTime.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
        alarmTime.set(Calendar.SECOND, 0);
        alarmTime.set(Calendar.MILLISECOND, 0);

        if (alarmTime.before(Calendar.getInstance())) {
            alarmTime.add(Calendar.DAY_OF_YEAR, 1);
        }

        java.text.DateFormat dateFmt = java.text.DateFormat.getDateTimeInstance(
                java.text.DateFormat.MEDIUM, java.text.DateFormat.LONG);

        Log.i(TAG, "Setting alarm at: " + dateFmt.format(alarmTime.getTime()));

        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(),
                               AlarmManager.INTERVAL_DAY, pi);
    }

}
 
Example 19
Source File: ServiceSinkhole.java    From tracker-control-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));
    startForeground(NOTIFY_WAITING, getWaitingNotification());

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (jni_context != 0) {
        Log.w(TAG, "Create with context=" + jni_context);
        jni_stop(jni_context);
        synchronized (jni_lock) {
            jni_done(jni_context);
            jni_context = 0;
        }
    }

    // Native init
    jni_context = jni_init(Build.VERSION.SDK_INT);
    Log.i(TAG, "Created context=" + jni_context);
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command", Process.THREAD_PRIORITY_FOREGROUND);
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log", Process.THREAD_PRIORITY_BACKGROUND);
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats", Process.THREAD_PRIORITY_BACKGROUND);
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
        registeredUser = true;
    }

    // Listen for idle mode state changes
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
        registeredIdleState = true;
    }

    // Listen for added/removed applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageChangedReceiver, ifPackage);
    registeredPackageChanged = true;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        try {
            listenNetworkChanges();
        } catch (Throwable ex) {
            Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            listenConnectivityChanges();
        }
    else
        listenConnectivityChanges();

    // Monitor networks
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    cm.registerNetworkCallback(
            new NetworkRequest.Builder()
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(),
            networkMonitorCallback);

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        pi = PendingIntent.getForegroundService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    else
        pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000, AlarmManager.INTERVAL_HALF_DAY, pi);
}
 
Example 20
Source File: PollReceiver.java    From ApkTrack with GNU General Public License v3.0 4 votes vote down vote up
public void scheduleAlarms(AlarmManager mgr, PendingIntent pi, Context ctxt)
{
    mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + 1000, DELAY, pi);
}