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:de.quist.app.errorreporter.ExceptionReportService.java

private void sendReport(Intent intent) throws UnsupportedEncodingException, NameNotFoundException {
    Log.v(TAG, "Got request to report error: " + intent.toString());
    Uri server = getTargetUrl();/*from   w  w  w .j  a va 2s  .c o  m*/

    boolean isManualReport = intent.getBooleanExtra(EXTRA_MANUAL_REPORT, false);
    boolean isReportOnFroyo = isReportOnFroyo();
    boolean isFroyoOrAbove = isFroyoOrAbove();
    if (isFroyoOrAbove && !isManualReport && !isReportOnFroyo) {
        // We don't send automatic reports on froyo or above
        Log.d(TAG, "Don't send automatic report on froyo");
        return;
    }

    Set<String> fieldsToSend = getFieldsToSend();

    String stacktrace = intent.getStringExtra(EXTRA_STACK_TRACE);
    String exception = intent.getStringExtra(EXTRA_EXCEPTION_CLASS);
    String message = intent.getStringExtra(EXTRA_MESSAGE);
    long availableMemory = intent.getLongExtra(EXTRA_AVAILABLE_MEMORY, -1l);
    long totalMemory = intent.getLongExtra(EXTRA_TOTAL_MEMORY, -1l);
    String dateTime = intent.getStringExtra(EXTRA_EXCEPTION_TIME);
    String threadName = intent.getStringExtra(EXTRA_THREAD_NAME);
    String extraMessage = intent.getStringExtra(EXTRA_EXTRA_MESSAGE);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    addNameValuePair(params, fieldsToSend, "exStackTrace", stacktrace);
    addNameValuePair(params, fieldsToSend, "exClass", exception);
    addNameValuePair(params, fieldsToSend, "exDateTime", dateTime);
    addNameValuePair(params, fieldsToSend, "exMessage", message);
    addNameValuePair(params, fieldsToSend, "exThreadName", threadName);
    if (extraMessage != null)
        addNameValuePair(params, fieldsToSend, "extraMessage", extraMessage);
    if (availableMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devAvailableMemory", availableMemory + "");
    if (totalMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devTotalMemory", totalMemory + "");

    PackageManager pm = getPackageManager();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
        addNameValuePair(params, fieldsToSend, "appVersionCode", packageInfo.versionCode + "");
        addNameValuePair(params, fieldsToSend, "appVersionName", packageInfo.versionName);
        addNameValuePair(params, fieldsToSend, "appPackageName", packageInfo.packageName);
    } catch (NameNotFoundException e) {
    }
    addNameValuePair(params, fieldsToSend, "devModel", android.os.Build.MODEL);
    addNameValuePair(params, fieldsToSend, "devSdk", android.os.Build.VERSION.SDK);
    addNameValuePair(params, fieldsToSend, "devReleaseVersion", android.os.Build.VERSION.RELEASE);

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(server.toString());
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    Log.d(TAG, "Created post request");

    try {
        httpClient.execute(post);
        Log.v(TAG, "Reported error: " + intent.toString());
    } catch (ClientProtocolException e) {
        // Ignore this kind of error
        Log.e(TAG, "Error while sending an error report", e);
    } catch (SSLException e) {
        Log.e(TAG, "Error while sending an error report", e);
    } catch (IOException e) {
        if (e instanceof SocketException && e.getMessage().contains("Permission denied")) {
            Log.e(TAG, "You don't have internet permission", e);
        } else {
            int maximumRetryCount = getMaximumRetryCount();
            int maximumExponent = getMaximumBackoffExponent();
            // Retry at a later point in time
            AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            int exponent = intent.getIntExtra(EXTRA_CURRENT_RETRY_COUNT, 0);
            intent.putExtra(EXTRA_CURRENT_RETRY_COUNT, exponent + 1);
            PendingIntent operation = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (exponent >= maximumRetryCount) {
                // Discard error
                Log.w(TAG, "Error report reached the maximum retry count and will be discarded.\nStacktrace:\n"
                        + stacktrace);
                return;
            }
            if (exponent > maximumExponent) {
                exponent = maximumExponent;
            }
            long backoff = (1 << exponent) * 1000; // backoff in ms
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + backoff, operation);
        }
    }
}

From source file:com.kaku.weac.fragment.AlarmClockOntimeFragment.java

/**
 * ??//from   ww w  . j a  v  a 2s .  c  om
 */
@TargetApi(19)
private void nap() {
    // ??X
    if (mNapTimesRan == mNapTimes) {
        return;
    }
    // ??1
    mNapTimesRan++;
    LogUtil.d(LOG_TAG, "??" + mNapTimesRan);

    // ???
    Intent intent = new Intent(getActivity(), AlarmClockBroadcast.class);
    intent.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock);
    intent.putExtra(WeacConstants.NAP_RAN_TIMES, mNapTimesRan);
    PendingIntent pi = PendingIntent.getBroadcast(getActivity(), -mAlarmClock.getId(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Activity.ALARM_SERVICE);
    // XXX
    // ?
    long nextTime = System.currentTimeMillis() + 1000 * 60 * mNapInterval;

    LogUtil.i(LOG_TAG, "??:" + mNapInterval + "");

    // ?194.4
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextTime, pi);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextTime, pi);
    }

    // ?
    Intent it = new Intent(getActivity(), AlarmClockNapNotificationActivity.class);
    it.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock);
    // FLAG_UPDATE_CURRENT ???
    // FLAG_ONE_SHOT ??
    PendingIntent napCancel = PendingIntent.getActivity(getActivity(), mAlarmClock.getId(), it,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // 
    CharSequence time = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(nextTime);

    // 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity());
    // PendingIntent
    Notification notification = builder.setContentIntent(napCancel)
            // ?
            .setDeleteIntent(napCancel)
            // 
            .setContentTitle(String.format(getString(R.string.xx_naping), mAlarmClock.getTag()))
            // 
            .setContentText(String.format(getString(R.string.nap_to), time))
            // ???
            .setTicker(String.format(getString(R.string.nap_time), mNapInterval))
            // ???
            .setSmallIcon(R.drawable.ic_nap_notification)
            // 
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setAutoCancel(true)
            // ??
            .setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.FLAG_SHOW_LIGHTS).build();
    /*        notification.defaults |= Notification.DEFAULT_LIGHTS;
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;*/

    // ???
    mNotificationManager.notify(mAlarmClock.getId(), notification);
}

From source file:com.android.launcher3.Utilities.java

public static void restart(Context context, int delay) {
    if (delay == 0) {
        delay = 1;/*from  w w  w .  j  a  v  a 2s .  c  om*/
    }
    Intent restartIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    restartIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    PendingIntent intent = PendingIntent.getActivity(context, 0, restartIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.RTC, java.lang.System.currentTimeMillis() + delay, intent);
    java.lang.System.exit(2);
}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

public ScheduledNotification scheduleNotification(String title, JSONObject options) {
    LOG.v(NotificationPlugin.TAG, "scheduleNotification: " + title);

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

    ScheduledNotification notification = new ScheduledNotification(title, options);

    long alarmTime = notification.at;

    if (alarmTime != 0) { //0 = uninitialized.

        saveNotification(notification);/*  w ww  .ja v  a  2s . c om*/

        LOG.v(NotificationPlugin.TAG, "create Intent: " + notification.tag);

        Intent intent = new Intent(context, TriggerReceiver.class);
        intent.setAction(notification.tag);

        PendingIntent pi = PendingIntent.getBroadcast(context, INTENT_REQUEST_CODE, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        LOG.v(NotificationPlugin.TAG, "schedule alarm for: " + alarmTime);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pi);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
        }
    } else {
        // No "at", trigger the notification right now.
        showNotification(notification);
    }

    return notification;
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private void registerForUpdates(boolean isRetry) {
    Calendar lastAttempt = getLastAttemptDate();
    Calendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

    int interval = getUpdateInterval(isRetry);

    if (lastAttempt == null || (now.getTimeInMillis() - lastAttempt.getTimeInMillis()) > interval) {
        // We've either never attempted an update, or we are passed the desired
        // time. Start an update now.
        Log.i(LOGTAG, "no update has ever been attempted, checking now");
        startUpdate(0);/*from   ww w.  jav a  2 s  .  c  o  m*/
        return;
    }

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (manager == null)
        return;

    PendingIntent pending = PendingIntent.getService(this, 0,
            new Intent(UpdateServiceHelper.ACTION_CHECK_FOR_UPDATE, null, this, UpdateService.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
    manager.cancel(pending);

    lastAttempt.setTimeInMillis(lastAttempt.getTimeInMillis() + interval);
    Log.i(LOGTAG, "next update will be at: " + lastAttempt.getTime());

    manager.set(AlarmManager.RTC_WAKEUP, lastAttempt.getTimeInMillis(), pending);
}

From source file:com.crearo.gpslogger.GpsLoggingService.java

/**
 * Sets up the auto email timers based on user preferences.
 *//*from   ww  w  . ja  v  a 2s.  c  o  m*/
@TargetApi(23)
public void setupAutoSendTimers() {
    LOG.debug("Setting up autosend timers. Auto Send Enabled - "
            + String.valueOf(preferenceHelper.isAutoSendEnabled()) + ", Auto Send Delay - "
            + String.valueOf(Session.getAutoSendDelay()));

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

        alarmIntent = new Intent(this, AlarmReceiver.class);
        cancelAlarm();

        PendingIntent sender = PendingIntent.getBroadcast(this, 0, alarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (Systems.isDozing(this)) {
            am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, sender);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
        }
        LOG.debug("Autosend alarm has been set");

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

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

private void ensureServiceStaysRunning() {
    // KitKat appears to have (in some cases) forgotten how to honor START_STICKY
    // and if the service is killed, it doesn't restart.  On an emulator & AOSP device, it restarts...
    // on my CM device, it does not - WTF?  So, we'll make sure it gets back
    // up and running in a minimum of 10 minutes.  We reset our timer on a handler every
    // 2 minutes...but since the handler runs on uptime vs. the alarm which is on realtime,
    // it is entirely possible that the alarm doesn't get reset.  So - we make it a noop,
    // but this will still count against the app as a wakelock when it triggers.  Oh well,
    // it should never cause a device wakeup.  We're also at SDK 19 preferred, so the alarm
    // mgr set algorithm is better on memory consumption which is good.
    // http://stackoverflow.com/a/20735519/1527491
    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        if (DEBUG)
            Log.d(TAG, "ensureServiceStaysRunning > setting alarm. [ Kitkat START_STICKY bug ]");
        // A restart intent - this never changes...        
        final int restartAlarmInterval = 10 * 60 * 1000;
        final int resetAlarmTimer = 1 * 60 * 1000;
        final Intent restartIntent = new Intent(this, MonitorService.class);
        restartIntent.putExtra(INTENT_ALARM_RESTART_SERVICE_DIED, true);
        final AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Handler restartServiceHandler = new Handler() {
            @Override//w  ww .j a  va2  s  . c om
            public void handleMessage(Message msg) {
                // Create a pending intent
                PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
                alarmMgr.set(AlarmManager.ELAPSED_REALTIME,
                        SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
                sendEmptyMessageDelayed(0, resetAlarmTimer);
            }
        };
        restartServiceHandler.sendEmptyMessageDelayed(0, 0);
    }
}

From source file:indrora.atomic.irc.IRCService.java

/**
 * Connect to the given server/*  w w w  . j a v a  2  s  .  c  om*/
 */
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) {
                if (alarmIntents == null)
                    return;
                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());
                X509TrustManager[] trustMgr = MemorizingTrustManager.getInstanceList(getApplicationContext());
                connection.setTrustManagers(trustMgr);

                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);

                NetworkInfo ninf = ((ConnectivityManager) (IRCService.this
                        .getSystemService(Service.CONNECTIVITY_SERVICE))).getActiveNetworkInfo();
                if (ninf == null) {
                    _isTransient = false;
                } else {
                    _isTransient = !(ninf.getState() == NetworkInfo.State.CONNECTED);
                }

                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 if (e instanceof SSLException) {
                    // This happens when we declined the SSL certificate most of the time
                    // We should check what really happened.
                    message = new Message("SSL negotiation failed: " + e.toString());
                } else {
                    message = new Message(
                            getString(R.string.could_not_connect, server.getHost(), server.getPort()) + ":\n"
                                    + e.getMessage());

                    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.MessageColor.ERROR);
                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.xperia64.rompatcher.MainActivity.java

@SuppressLint("NewApi")
@Override/*from www . java 2  s.co  m*/
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
    case PERMISSION_REQUEST: {
        // If request is cancelled, the result arrays are empty.
        boolean good = true;
        if (permissions.length != NUM_PERMISSIONS || grantResults.length != NUM_PERMISSIONS) {
            good = false;
        }

        for (int i = 0; i < grantResults.length && good; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                good = false;
            }
        }
        if (!good) {

            // permission denied, boo! Disable the app.
            new AlertDialog.Builder(MainActivity.this).setTitle("Error")
                    .setMessage("ROM Patcher cannot proceed without these permissions")
                    .setPositiveButton("OK", new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MainActivity.this.finish();
                        }

                    }).setCancelable(false).show();
        } else {
            if (!Environment.getExternalStorageDirectory().canRead()) {
                // Buggy emulator? Try restarting the app
                AlarmManager alm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
                alm.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(this,
                        237462, new Intent(this, MainActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK));
                System.exit(0);
            }
        }
        return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
    }
}

From source file:com.actinarium.nagbox.service.NagboxService.java

private void rescheduleAlarm() {
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Prepare pending intent. Setting, updating, or cancelling the alarm - we need it in either case
    Intent intent = new Intent(this, NagAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    long nextTimestamp = NagboxDbOps.getClosestNagTimestamp(mDatabase);
    if (nextTimestamp == 0) {
        alarmManager.cancel(pendingIntent);
    } else {//www.  jav a 2s.c o  m
        // todo: deal with exact/inexact reminders later
        if (Build.VERSION.SDK_INT >= 23) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextTimestamp, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setWindow(AlarmManager.RTC_WAKEUP, nextTimestamp, ALARM_TOLERANCE, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextTimestamp, pendingIntent);
        }
    }
}