Example usage for android.app AlarmManager RTC_WAKEUP

List of usage examples for android.app AlarmManager RTC_WAKEUP

Introduction

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

Prototype

int RTC_WAKEUP

To view the source code for android.app AlarmManager RTC_WAKEUP.

Click Source Link

Document

Alarm time in System#currentTimeMillis System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.

Usage

From source file:com.monkey.entonado.MainActivity.java

/**
 * OnResume//ww w.j av a  2 s  . com
 * register the broadcast receiver with the intent values to be matched
 */
@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mReceiver, mIntentFilter);
    CountDownTimer t = new CountDownTimer(1000, 500) {

        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {
            if (intentoConectar) {
                mostrarMensaje(mensajeConexion);
                intentoConectar = false;
            } else if (intentoEnviarLista) {
                String mensaje = "";
                boolean entro = false;
                if (mensajeConexion == null) {
                    mensaje = "Estas desconectado";

                } else if (mensajeConexion.equals("desconectado")) {
                    mensaje = "Estas desconectado";

                } else if (mensajeConexion.equals("Estas conectado!")) {
                    mensaje = "La lista ha sido enviada";
                    Intent in = new Intent(MainActivity.this, AlarmReciever.class);
                    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, in,
                            PendingIntent.FLAG_ONE_SHOT);
                    entro = true;
                    System.out.println("puso alarma");

                    AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
                    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 60, pi);
                } else {
                    mensaje = mensajeConexion;
                }
                if (!entro)
                    mostrarMensaje(mensaje);
                intentoEnviarLista = false;
            }
        }
    }.start();
}

From source file:org.videolan.vlc.gui.video.AdvOptionsDialog.java

public static void setSleep(Context context, Calendar time) {
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(VLCApplication.SLEEP_INTENT);
    PendingIntent sleepPendingIntent = PendingIntent.getBroadcast(VLCApplication.getAppContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    if (time != null) {
        alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), sleepPendingIntent);
    } else {/* ww w.j a v a 2  s .c  o m*/
        alarmMgr.cancel(sleepPendingIntent);
    }
    VLCApplication.sPlayerSleepTime = time;
}

From source file:org.opensilk.music.ui2.LauncherActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Timber.v("onActivityResult");
    switch (requestCode) {
    case StartActivityForResult.APP_REQUEST_SETTINGS:
        switch (resultCode) {
        case ActivityResult.RESULT_RESTART_APP:
            // Hack to force a refresh for our activity for eg theme change
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            PendingIntent pi = PendingIntent.getActivity(this, 0, getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(getBaseContext().getPackageName()),
                    PendingIntent.FLAG_CANCEL_CURRENT);
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 700, pi);
            finish();/*from  www . j  a v a  2s  . c  om*/
            break;
        case ActivityResult.RESULT_RESTART_FULL:
            killServiceOnExit = true;
            onActivityResult(StartActivityForResult.APP_REQUEST_SETTINGS, ActivityResult.RESULT_RESTART_APP,
                    data);
            break;
        }
        break;
    case StartActivityForResult.PLUGIN_REQUEST_LIBRARY:
    case StartActivityForResult.PLUGIN_REQUEST_SETTINGS:
        mBus.post(new ActivityResult(data, requestCode, resultCode));
        break;
    default:
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:com.first.akashshrivastava.showernow.ShowerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_shower_activity);

    /*Launching BootReceiver to test
    Intent playIntent = new Intent(getApplicationContext(), BootReceiver.class);
    startActivity(playIntent);/*w  ww. jav  a  2s.  c om*/
    */

    //Mobile ads initialization....The long number is the AdID, can be found on AdMob -  ca-app-pub-8782530512283806/2988799979
    MobileAds.initialize(getApplicationContext(), "ca-app-pub-8782530512283806/2988799979");
    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    //Facebook SDK initialization...
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);

    shareDialog = new ShareDialog(this);

    mDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAuth = FirebaseAuth.getInstance();

    final ImageView genderImage = (ImageView) findViewById(R.id.imageGender);

    guyText = (TextView) findViewById(R.id.guyText);

    topText = (TextView) findViewById(R.id.textView2);

    SharedPreferences prefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);

    extraAge = prefs.getInt("age", 0);
    extraFluffiness = prefs.getString("fluffiness", "");
    extraGender = prefs.getString("gender", "");
    extraOldTime = prefs.getLong("time", 0);
    extraSteps = prefs.getFloat("stepsBoot", 0);

    switch (extraGender) {
    case "male":
        genderImage.setImageResource(R.drawable.male_white_outline);
        break;
    case "female":
        genderImage.setImageResource(R.drawable.female_white_outline);
        break;
    case "other":
        genderImage.setImageResource(R.drawable.other_white_outline);
        break;
    }

    genderImage.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) { //set alarm
            //Swith ccase
            switch (event.getAction()) {

            case MotionEvent.ACTION_UP:
                // PRESSED ..PRESSED

                if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.female_white_outline_pressed).getConstantState()) {
                    genderImage.setImageResource(R.drawable.female_white_outline);
                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.male_white_outline_pressed).getConstantState()) {
                    genderImage.setImageResource(R.drawable.male_white_outline);
                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.other_white_outline_pressed).getConstantState()) {
                    genderImage.setImageResource(R.drawable.other_white_outline);
                }

                //Resets the wave after shower..this is not getting called for some reason....
                waveProgressbar.setCurrent(0, "");
                guyText.setText("0 %");
                waveProgressbar.setVisibility(View.INVISIBLE);

                topText.setText("You have showered! \n When the wave hits 100% its time for your next shower ");

                if (fluffiness != null && gotSteps) {
                    Calendar cal = Calendar.getInstance();
                    Intent activate = new Intent(ShowerActivity.this, AlarmReceiver.class);
                    activate.putExtra("age", age);
                    activate.putExtra("fluffiness", fluffiness);
                    activate.putExtra("gender", gender);
                    activate.putExtra("steps", steps);
                    activate.putExtra("time", System.currentTimeMillis());

                    AlarmManager alarms;
                    PendingIntent alarmIntent = PendingIntent.getBroadcast(ShowerActivity.this, 0, activate,
                            FLAG_CANCEL_CURRENT);
                    alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarms.cancel(alarmIntent);

                    alarms.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 5000, 1000 * 60,
                            alarmIntent);//sets the alarm

                    mDatabaseReference.child("User").child(mFirebaseAuth.getCurrentUser().getUid())
                            .child("Steps").setValue(steps);//sets old steps
                    oldSteps = steps;
                    mDatabaseReference.child("User").child(mFirebaseAuth.getCurrentUser().getUid())
                            .child("Time").setValue(System.currentTimeMillis());
                    oldTime = System.currentTimeMillis();
                    newUser = false;

                    SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putInt("age", age);
                    editor.putString("fluffiness", fluffiness);
                    editor.putString("gender", gender);
                    editor.putFloat("steps", steps);
                    editor.putLong("time", System.currentTimeMillis());
                    editor.putFloat("stepsBoot", 0);
                    editor.putBoolean("bootStart", true);
                    editor.apply();

                } else if (!gotSteps) {
                    Toast.makeText(getApplicationContext(), "Waiting for steps", Toast.LENGTH_SHORT).show();
                }
                return true; // if you want to handle the touch event

            case MotionEvent.ACTION_DOWN:
                // RELEASED..RELEASED..

                if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.female_white_outline).getConstantState()) {
                    genderImage.setImageResource(R.drawable.female_white_outline_pressed);

                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.male_white_outline).getConstantState()) {
                    genderImage.setImageResource(R.drawable.male_white_outline_pressed);

                } else if (genderImage.getDrawable().getConstantState() == getResources()
                        .getDrawable(R.drawable.other_white_outline).getConstantState()) {
                    genderImage.setImageResource(R.drawable.other_white_outline_pressed);

                }

                return true; // if you want to handle the touch event
            }
            //Switch case end bracket

            return false;
        }

    });

    createWave();
    setMenuColor();
    setupStepcount();
    setWaveHeight();

    FloatingActionButton editDetails = (FloatingActionButton) findViewById(R.id.menu_item4); //edit user information. Goes to main activity
    editDetails.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            /*
            Fragment fragment = new Fragment();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(ShowerActivity.java);
            transaction.addToBackStack(ShowerActivity.java);
            transaction.commit();
                    
            */
            //Fragment B at pos 2 should open when edit details is pressed..
            Intent i = new Intent(ShowerActivity.this, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }
    });

    FloatingActionButton fabmenuDeleteAccount = (FloatingActionButton) findViewById(R.id.delete_Account);
    fabmenuDeleteAccount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog();
        }
    });

    FloatingActionButton fabMenuItem1 = (FloatingActionButton) findViewById(R.id.menu_item);
    fabMenuItem1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            /*ComponentName receiver = new ComponentName(ShowerActivity.this, AlarmReceiver.class); // alarms.cancel(alarmIntent);??
            PackageManager pm = ShowerActivity.this.getPackageManager();
            pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
                    
            stopService(new Intent(StepCountService.STEP_COUNT_SERVICE));*/

            //mFirebaseAuth.getCurrentUser().getUid() =null;

            SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt("age", 0);
            editor.putString("fluffiness", "");
            editor.putString("gender", "");
            editor.putFloat("steps", 0);
            editor.putLong("time", 0);
            editor.putFloat("stepsBoot", 0);
            editor.putBoolean("bootStart", false);
            editor.apply();

            Intent activate = new Intent(ShowerActivity.this, AlarmReceiver.class);
            PendingIntent alarmIntent = PendingIntent.getBroadcast(ShowerActivity.this, 0, activate,
                    FLAG_CANCEL_CURRENT);

            AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarms.cancel(alarmIntent);

            stopService(new Intent(ShowerActivity.this, StepCountService.class));

            mFirebaseAuth.getInstance().signOut();
            Intent i = new Intent(ShowerActivity.this, LoginActivity.class);
            startActivity(i);
        }
    });

    final FloatingActionButton shareButton = (FloatingActionButton) findViewById(R.id.shareButton);
    shareButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            String shareBody = "Check out this showering app at: https://play.google.com/store/apps/details?id=com.first.akashshrivastava.showernow \n";
            String shareSubString = "An app that tells you when you should shower and apparently keeps you clean";
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubString);
            shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
            startActivity(Intent.createChooser(shareIntent, " Share using the following"));

        }
    });

    mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snap) {

            try {
                if ((!(mFirebaseAuth.getCurrentUser().getUid().isEmpty()))
                        && snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                                .getValue().toString().equalsIgnoreCase("female")) {
                    genderImage.setImageResource(R.drawable.female_white_outline);
                } else if (snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                        .getValue().toString().equalsIgnoreCase("male")) {
                    genderImage.setImageResource(R.drawable.male_white_outline);
                } else if (snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                        .getValue().toString().equalsIgnoreCase("other")) {
                    genderImage.setImageResource(R.drawable.other_white_outline);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            age = Integer.parseInt(snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid())
                    .child("Age").getValue().toString());//gotta get int

            fluffiness = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                    .getValue().toString();
            gender = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("gender")
                    .getValue().toString();

            if (snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("Time").exists()) {
                oldTime = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("Time")
                        .getValue(Long.class);
                oldSteps = snap.child("User").child(mFirebaseAuth.getCurrentUser().getUid()).child("Steps")
                        .getValue(float.class);

            } else {
                newUser = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

From source file:com.brayanarias.alarmproject.receiver.AlarmReceiver.java

public static void dismissAlarm(int alarmId, int minutes, Context context) {
    try {/* ww w.j  a  v  a 2  s  .  c  om*/
        DataBaseManager dataBaseManager = DataBaseManager.getInstance(context);
        Alarm alarm = AlarmDataBase.getAlarmById(dataBaseManager, alarmId);
        PendingIntent pendingIntent = createPendingIntent(context, alarm);
        AlarmManager alarmManager = getAlarmManager(context);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minutes);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(),
                    pendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
    } catch (Exception e) {
        Log.e(tag, e.getMessage(), e);
    }
}

From source file:edu.mit.media.funf.configured.ConfiguredPipeline.java

private void scheduleAlarm(String action, long delayInSeconds) {
    Intent i = new Intent(this, getClass());
    i.setAction(action);//from  w  ww  . j a v a2s  .co m
    boolean noAlarmExists = (PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE) == null);
    if (noAlarmExists) {
        PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long delayInMilliseconds = Utils.secondsToMillis(delayInSeconds);
        long startTimeInMilliseconds = System.currentTimeMillis() + delayInMilliseconds;
        Log.i(TAG, "Scheduling alarm for '" + action + "' at " + Utils.millisToSeconds(startTimeInMilliseconds)
                + " and every " + delayInSeconds + " seconds");
        // Inexact repeating doesn't work unlesss interval is 15, 30 min, or 1, 6, or 24 hours
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, startTimeInMilliseconds, delayInMilliseconds,
                pi);
    }
}

From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    if (context == null || intent == null) {
        Logger.error("AlarmReceiver", "onReceive(Context " + (context == null ? "null," : ",") + " Intent "
                + (intent == null ? "null)" : ")"));
        return;/*from www  .  j a  va 2 s.c  o  m*/
    }

    // Set Context
    mContext = context;

    // Get shared preferences.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    // Check internet availability and only in that case start actions.
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    final String action = intent.getAction();
    // Catch Network change state.
    if (!TextUtils.isEmpty(action) && action.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
        // If internet connection established
        if (isConnected) {
            // If didn't missed last update of data due to network issues do nothing,
            // otherwise proceed with data updating.
            final boolean missUpdateDueToNetworkIssue = sp
                    .getBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, false);
            if (!missUpdateDueToNetworkIssue)
                return;
        }
        // If user switch off Internet connection do not proceed.
        else
            return;
    }
    // Check Boot state.
    else if (!TextUtils.isEmpty(action) && action.equals("android.intent.action.BOOT_COMPLETED")) {
        // Get stored alarm time.
        final long nextAlarmTime = PreferenceUtils.getDataLong(context,
                PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1);
        if (nextAlarmTime != -1) {
            // Set new alarm, as after reboot alarm was switched off.
            if (mAlarmManager == null)
                mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            Intent alarmIntent = new Intent(context, AlarmReceiver.class);
            if (mAlarmIntent == null)
                mAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

            // Enable boot receiver
            ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

            final int ui = DialogSettings.getUpdateInterval(context);
            AlarmType type = ui == DialogSettings.DAILY ? AlarmType.DAILY
                    : ui == DialogSettings.WEEKLY ? AlarmType.WEEKLY : AlarmType.MONTHLY;

            mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nextAlarmTime, type.getValue(),
                    mAlarmIntent);
        }
        return;
    }
    // When alarm rise we appears in the block below.
    else {
        Logger.beep();
        Logger.beep();
        Logger.beep();
        // Calculating next alarm time.
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        final int updateInterval = DialogSettings.getUpdateInterval(context);
        if (updateInterval == DialogSettings.DAILY)
            calendar.add(Calendar.DATE, 1);
        else if (updateInterval == DialogSettings.WEEKLY)
            calendar.add(Calendar.DATE, 7);
        else if (updateInterval == DialogSettings.MONTHLY)
            calendar.add(Calendar.MONTH, 1);
        else
            Logger.error("AlarmReceiver", "Unknown Update Interval.");

        // Next alarm time.
        final long nextAlarmTimeInMillis = calendar.getTimeInMillis();
        // Store next alarm time for further use.
        PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, nextAlarmTimeInMillis);
    }

    if (!isConnected) {
        Logger.debug("AlarmReceiver", "No Internet connection, while receiving Alarm message");
        // If no internet connecting schedule data update, as soon
        // as internet connection will be available.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, true);
        ed.apply();
        return;
    }

    final String cerNum = sp.getString(MainActivity.CER_NUMBER, MainActivity.EMPTY_STRING);
    final String regNum = sp.getString(MainActivity.REG_NUMBER, MainActivity.EMPTY_STRING);
    final boolean login = sp.getBoolean(MainActivity.AUTO_LOGIN, false);
    if (!login) { // If no auto login user detected.
        Logger.debug("AlarmReceiver", "Why we enter this case if no auto login users detected?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        return;
    }

    if (TextUtils.isEmpty(cerNum) || TextUtils.isEmpty(regNum)) {
        Logger.debug("AlarmReceiver", "Why we enter this case if both data are null or empty?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        // Remove auto login.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.AUTO_LOGIN, false);
        ed.apply();
        return;
    }

    // Start downloading data from internet.
    Submitter submitter = new Submitter(cerNum, regNum, this);
    submitter.executeOnExecutor(Executors.newSingleThreadExecutor());
}

From source file:org.svij.taskwarriorapp.TasksActivity.java

@Override
protected void onResume() {
    super.onResume();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long date_long = prefs.getLong("notifications_alarm_time", System.currentTimeMillis());

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(date_long);

    if (!calendar.getTime().before(new Date())) {
        am.cancel(pi);/* w  w  w  .  ja  v  a  2  s. com*/
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY, pi);
    }

}

From source file:com.poloure.simplerss.FeedsActivity.java

private void setServiceIntent(int state) {
    // Load the ManageFeedsRefresh boolean value from settings.
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    if (!pref.getBoolean("refreshing_enabled", false) && ALARM_SERVICE_START == state) {
        return;// w w w.j  a v a  2 s.c om
    }

    // Create intent, turn into pending intent, and get the alarm manager.
    Intent intent = new Intent(this, ServiceUpdate.class);

    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    // Depending on the state string, start or stop the service.
    if (ALARM_SERVICE_START == state) {
        String intervalString = pref.getString("refresh_interval", "120");

        long interval = Long.parseLong(intervalString) * MINUTE_VALUE;
        long next = System.currentTimeMillis() + interval;
        am.setRepeating(AlarmManager.RTC_WAKEUP, next, interval, pendingIntent);
    } else if (ALARM_SERVICE_STOP == state) {
        am.cancel(pendingIntent);
    }
}

From source file:fr.paug.droidcon.service.SessionAlarmService.java

private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) {

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(NOTIFICATION_ID);//from w  ww  . ja  va  2s .  c o m
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart) {
        LOGD(TAG, "Not scheduling alarm because target time is in the past: " + sessionStart);
        return;
    }

    // By default, sets alarm to go off at 10 minutes before session start time.  If alarm
    // offset is provided, alarm is set to go off by that much time from now.
    long alarmTime;
    if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
        alarmTime = sessionStart - MILLI_TEN_MINUTES;
    } else {
        alarmTime = currentTime + alarmOffset;
    }

    LOGD(TAG, "Scheduling alarm for " + alarmTime + " = " + (new Date(alarmTime)).toString());

    final Intent notifIntent = new Intent(ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class);
    // Setting data to ensure intent's uniqueness for different session start times.
    notifIntent.setData(
            new Uri.Builder().authority("fr.paug.droidcon").path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    LOGD(TAG, "-> Intent extra: session start " + sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    LOGD(TAG, "-> Intent extra: session end " + sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    LOGD(TAG, "-> Intent extra: session alarm offset " + alarmOffset);
    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Schedule an alarm to be fired to notify user of added sessions are about to begin.
    LOGD(TAG, "-> Scheduling RTC_WAKEUP alarm at " + alarmTime);
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}