Example usage for android.app AlarmManager set

List of usage examples for android.app AlarmManager set

Introduction

In this page you can find the example usage for android.app AlarmManager set.

Prototype

public void set(@AlarmType int type, long triggerAtMillis, PendingIntent operation) 

Source Link

Document

Schedule an alarm.

Usage

From source file:org.adblockplus.android.AdblockPlus.java

/**
 * Sets Alarm to call updater after specified number of minutes or after one
 * day if/*from  w  w w.j  a  va  2s.  co m*/
 * minutes are set to 0.
 * 
 * @param minutes
 *          number of minutes to wait
 */
public void scheduleUpdater(int minutes) {
    Calendar updateTime = Calendar.getInstance();

    if (minutes == 0) {
        // Start update checks at 10:00 GMT...
        updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
        updateTime.set(Calendar.HOUR_OF_DAY, 10);
        updateTime.set(Calendar.MINUTE, 0);
        // ...next day
        updateTime.add(Calendar.HOUR_OF_DAY, 24);
        // Spread out the mass downloading? for 6 hours
        updateTime.add(Calendar.MINUTE, (int) (Math.random() * 60 * 6));
    } else {
        updateTime.add(Calendar.MINUTE, minutes);
    }

    Intent updater = new Intent(this, AlarmReceiver.class);
    PendingIntent recurringUpdate = PendingIntent.getBroadcast(this, 0, updater,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // Set non-waking alarm
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.set(AlarmManager.RTC, updateTime.getTimeInMillis(), recurringUpdate);
}

From source file:org.pixmob.freemobile.netstat.MonitorService.java

@Override
public void onTaskRemoved(Intent rootIntent) {
    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        // If task was removed, we should launch the service again.
        if (DEBUG)
            Log.d(TAG, "onTaskRemoved > setting alarm to restart service [ Kitkat START_STICKY bug ]");
        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext()
                .getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
    }/*from  w  ww . j a v  a  2 s.  c om*/

}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Restart the current app. Supply the class to start on startup
 *///  w  w w.ja va 2 s . co m
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);
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

private String alarmSetting(String settingString) {
    if (settingString.contains("set alarm")) {
        /** Set Alarm **/

        String hour = settingString.substring(settingString.indexOf("#") + 1, settingString.indexOf("*"));
        String minute = settingString.substring(settingString.indexOf("*") + 1, settingString.indexOf("|"));

        Log.d("timePicker", hour + ":" + minute);

        int hr = Integer.parseInt(hour);
        int min = Integer.parseInt(minute);

        Log.d("Alarm", "hr:" + hr + "min:" + min);

        Calendar cal = Calendar.getInstance();
        // add minutes to the calendar object
        ////  ww w .  j  a v a 2  s . c om
        cal.set(Calendar.HOUR_OF_DAY, hr);
        cal.set(Calendar.MINUTE, min);
        cal.set(Calendar.SECOND, 0);
        // cal.add(Calendar.MINUTE, 1);
        Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
        alarmintent.putExtra("title", "Alarm for " + hour + ":" + minute);
        alarmintent.putExtra("note", "Touch to turn off Alarm");
        // HELLO_ID is a static variable that must be
        // initialised at the BEGINNING OF CLASS with 1;

        PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID, alarmintent,
                PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
        // VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT...
        // this will send correct extra's informations
        // to
        // AlarmReceiver Class
        // Get the AlarmManager service

        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
        Log.i("Alarm", "AlarmSet" + cal.toString());

        // /** Auto-sync **/
        //
        // if (!ContentResolver.getMasterSyncAutomatically())
        // ContentResolver.setMasterSyncAutomatically(true);
        // else {
        // ContentResolver.setMasterSyncAutomatically(false);
        // }

        return ("AlarmSet for : " + hour + ":" + min + "\n");

    }
    return ("");

}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Restart the application after 100ms//from  w  w  w  .  ja  va2 s  . c o m
 *
 * @param activity activity
 */
public static void restartApp(Activity activity) {
    // clear the preferences
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = preferences.edit();

    // use the preference to avoid infinite relaunch on some devices
    // the culprit activity is restarted when System.exit is called.
    // so called it once to fix it
    if (!preferences.getBoolean(RESTART_IN_PROGRESS_KEY, false)) {
        CommonActivityUtils.displayToast(activity.getApplicationContext(),
                "Restart the application (low memory)");

        Log.e(LOG_TAG, "Kill the application");
        editor.putBoolean(RESTART_IN_PROGRESS_KEY, true);
        editor.commit();

        PendingIntent mPendingIntent = PendingIntent.getActivity(activity, 314159,
                new Intent(activity, LoginActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

        // so restart the application after 100ms
        AlarmManager mgr = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);

        System.exit(0);
    } else {
        Log.e(LOG_TAG, "The application is restarting, please wait !!");
        activity.finish();
    }
}

From source file:org.ozonecity.gpslogger2.GpsLoggingService.java

/**
 * Sets up the auto email timers based on user preferences.
 *//* www. ja  v a2  s.com*/
public void SetupAutoSendTimers() {
    tracer.debug(
            "Setting up autosend timers. Auto Send Enabled - " + String.valueOf(AppSettings.isAutoSendEnabled())
                    + ", Auto Send Delay - " + String.valueOf(Session.getAutoSendDelay()));

    if (AppSettings.isAutoSendEnabled() && Session.getAutoSendDelay() > 0) {
        long triggerTime = System.currentTimeMillis() + (long) (Session.getAutoSendDelay() * 60 * 1000);

        alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
        CancelAlarm();

        PendingIntent sender = PendingIntent.getBroadcast(this, 0, alarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
        tracer.debug("Autosend alarm has been set");

    } else {
        if (alarmIntent != null) {
            tracer.debug("alarmIntent was null, canceling alarm");
            CancelAlarm();
        }
    }
}

From source file:org.numixproject.hermes.irc.IRCService.java

/**
 * Connect to the given server//from www  . j  a  v  a  2  s  . co  m
 */
public void connect(final Server server) {
    final int serverId = server.getId();
    final int reconnectInterval = settings.getReconnectInterval() * 60000;
    final IRCService service = this;

    if (settings.isReconnectEnabled()) {
        server.setMayReconnect(true);
    }

    new Thread("Connect thread for " + server.getTitle()) {
        @Override
        public void run() {
            synchronized (alarmIntentsLock) {
                alarmIntents.remove(serverId);
                ReconnectReceiver lastReceiver = alarmReceivers.remove(serverId);
                if (lastReceiver != null) {
                    unregisterReceiver(lastReceiver);
                }
            }

            if (settings.isReconnectEnabled() && !server.mayReconnect()) {
                return;
            }

            try {
                IRCConnection connection = getConnection(serverId);

                connection.setNickname(server.getIdentity().getNickname());
                connection.setAliases(server.getIdentity().getAliases());
                connection.setIdent(server.getIdentity().getIdent());
                connection.setRealName(server.getIdentity().getRealName());
                connection.setUseSSL(server.useSSL());

                if (server.getCharset() != null) {
                    connection.setEncoding(server.getCharset());
                }

                if (server.getAuthentication().hasSaslCredentials()) {
                    connection.setSaslCredentials(server.getAuthentication().getSaslUsername(),
                            server.getAuthentication().getSaslPassword());
                }

                if (server.getPassword() != "") {
                    connection.connect(server.getHost(), server.getPort(), server.getPassword());
                } else {
                    connection.connect(server.getHost(), server.getPort());
                }
            } catch (Exception e) {
                server.setStatus(Status.DISCONNECTED);

                Intent sIntent = Broadcast.createServerIntent(Broadcast.SERVER_UPDATE, serverId);
                sendBroadcast(sIntent);

                IRCConnection connection = getConnection(serverId);

                Message message;

                if (e instanceof NickAlreadyInUseException) {
                    message = new Message(getString(R.string.nickname_in_use, connection.getNick()));
                    server.setMayReconnect(false);
                } else if (e instanceof IrcException) {
                    message = new Message(
                            getString(R.string.irc_login_error, server.getHost(), server.getPort()));
                    server.setMayReconnect(false);
                } else {
                    message = new Message(
                            getString(R.string.could_not_connect, server.getHost(), server.getPort()));
                    if (settings.isReconnectEnabled()) {
                        Intent rIntent = new Intent(Broadcast.SERVER_RECONNECT + serverId);
                        PendingIntent pendingRIntent = PendingIntent.getBroadcast(service, 0, rIntent, 0);
                        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                        ReconnectReceiver receiver = new ReconnectReceiver(service, server);
                        synchronized (alarmIntentsLock) {
                            alarmReceivers.put(serverId, receiver);
                            registerReceiver(receiver, new IntentFilter(Broadcast.SERVER_RECONNECT + serverId));
                            am.set(AlarmManager.ELAPSED_REALTIME,
                                    SystemClock.elapsedRealtime() + reconnectInterval, pendingRIntent);
                            alarmIntents.put(serverId, pendingRIntent);
                        }
                    }
                }

                message.setColor(Message.COLOR_RED);
                message.setIcon(R.drawable.error);
                server.getConversation(ServerInfo.DEFAULT_NAME).addMessage(message);

                Intent cIntent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_MESSAGE, serverId,
                        ServerInfo.DEFAULT_NAME);
                sendBroadcast(cIntent);
            }
        }
    }.start();
}

From source file:com.android.development.Connectivity.java

private void scheduleAlarm(long delayMs, String eventType) {
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(CONNECTIVITY_TEST_ALARM);

    i.putExtra(TEST_ALARM_EXTRA, eventType);
    i.putExtra(TEST_ALARM_ON_EXTRA, Long.toString(mSCOnDuration));
    i.putExtra(TEST_ALARM_OFF_EXTRA, Long.toString(mSCOffDuration));
    i.putExtra(TEST_ALARM_CYCLE_EXTRA, Integer.toString(mSCCycleCount));

    PendingIntent p = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayMs, p);
}

From source file:edu.mit.media.funf.probe.Probe.java

private void updateInternalRequestsPendingIntent() {
    PendingIntent internalPendingIntent = PendingIntent.getService(this, 0, requestsIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Keep the pending intent valid, by having the alarm clock keep a reference to it
    AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
    manager.set(AlarmManager.RTC, System.currentTimeMillis() + FAR_IN_FUTURE_MILLIS, internalPendingIntent);
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

public JSONObject stopThread(String threadId) {

    THREAD_ID thread = THREAD_ID.valueOf(threadId);
    Thread myThread = null;/*w w  w .  j av  a2s  .  co  m*/

    switch (thread) {

    case unpack_apk:
        myThread = m_unpackApkThread;
        break;
    case dex2jar:
        myThread = m_dex2jarThread;
        break;
    case optimize_dex:
        myThread = m_optimizeDexThread;
        break;
    case cfr:
        myThread = m_cfrThread;
        break;
    case jadx:
        myThread = m_jadxThread;
        break;
    case fern_flower:
        myThread = m_fernThread;
        break;
    default:// do nothing
    }

    //        if( myThread != null){
    //                myThread.currentThread().stop();// deprecated as of API 16 jellybean
    //            myThread.currentThread().interrupt(); // not working, does not stop thread
    //        }

    /**
     * Not the best solution but attempts to selectively stop individual threads do not
     * seem to work. We need need a more robust solution for long running process management.
     */
    Intent mStartActivity = new Intent(m_ctx, com.nuvolect.deepdive.main.MainActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(m_ctx, mPendingIntentId, mStartActivity,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) m_ctx.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);

    Runtime.getRuntime().exit(0);

    return getStatus();
}