Example usage for android.app PendingIntent getBroadcast

List of usage examples for android.app PendingIntent getBroadcast

Introduction

In this page you can find the example usage for android.app PendingIntent getBroadcast.

Prototype

public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will perform a broadcast, like calling Context#sendBroadcast(Intent) Context.sendBroadcast() .

Usage

From source file:com.androidinspain.deskclock.alarms.AlarmNotifications.java

static synchronized void showMissedNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying missed notification for alarm instance: " + instance.mId);

    String label = instance.mLabel;
    String alarmTime = AlarmUtils.getFormattedTime(context, instance.getAlarmTime());
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setShowWhen(false)
            .setContentTitle(context.getString(com.androidinspain.deskclock.R.string.alarm_missed_title))
            .setContentText(instance.mLabel.isEmpty() ? alarmTime
                    : context.getString(com.androidinspain.deskclock.R.string.alarm_missed_text, alarmTime,
                            label))/*from  w  w w .java 2  s  .  c om*/
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background))
            .setSortKey(createSortKey(instance))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm)
            .setPriority(NotificationCompat.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setLocalOnly(true);

    if (Utils.isNOrLater()) {
        builder.setGroup(MISSED_GROUP_KEY);
    }

    final int id = instance.hashCode();

    // Setup dismiss intent
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    builder.setDeleteIntent(
            PendingIntent.getService(context, id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content intent
    Intent showAndDismiss = AlarmInstance.createIntent(context, AlarmStateManager.class, instance.mId);
    showAndDismiss.putExtra(EXTRA_NOTIFICATION_ID, id);
    showAndDismiss.setAction(AlarmStateManager.SHOW_AND_DISMISS_ALARM_ACTION);
    builder.setContentIntent(
            PendingIntent.getBroadcast(context, id, showAndDismiss, PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    final Notification notification = builder.build();
    nm.notify(id, notification);
    updateMissedAlarmGroupNotification(context, -1, notification);
}

From source file:com.google.android.libraries.cast.companionlibrary.notification.VideoCastNotificationService.java

/**
 * Returns the {@link NotificationCompat.Action} for rewinding the current media by
 * {@code millis} milliseconds./*from   www.j  a  v a2 s  . co  m*/
 */
protected NotificationCompat.Action getRewindAction(long millis) {
    Intent intent = new Intent(ACTION_REWIND);
    intent.setPackage(getPackageName());
    intent.putExtra(EXTRA_FORWARD_STEP_MS, (int) -millis);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    int iconResourceId = R.drawable.ic_notification_rewind_48dp;
    if (millis == TEN_SECONDS_MILLIS) {
        iconResourceId = R.drawable.ic_notification_rewind10_48dp;
    } else if (millis == THIRTY_SECONDS_MILLIS) {
        iconResourceId = R.drawable.ic_notification_rewind30_48dp;
    }
    return new NotificationCompat.Action.Builder(iconResourceId, getString(R.string.ccl_rewind), pendingIntent)
            .build();
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

@Override
public void onClick(View view) {
    int id = view.getId();
    ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
    switch (id) {
    case R.id.chat_send:

        smiliesShell.setVisibility(View.GONE);
        EditText message = (EditText) findViewById(R.id.chat_text);
        String messageT = message.getText().toString();
        if (messageT.length() == 0) {
            Toast.makeText(this, R.string.no_message, Toast.LENGTH_SHORT).show();
            return;
        }/* w  w w .j  a v a2s.  com*/
        if (messageT.length() > 140) {
            Toast.makeText(this, R.string.message_too_long, Toast.LENGTH_SHORT).show();
            return;
        }
        nvp.add(new BasicNameValuePair("message", messageT));
        doSubmit("chatform", nvp, true);
        doChatScroll = true;
        break;
    case R.id.med_send:
        int w = walkingPicker.getValue();
        int s = sittingPicker.getValue();

        if (w == 0 && s == 0) {
            Toast.makeText(this, R.string.no_time, Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("walking", w);
        editor.putInt("sitting", s);
        editor.apply();

        lastWalking = w * 5;
        lastSitting = s * 5;

        startMeditating = true;

        nvp.add(new BasicNameValuePair("walking", lastWalking + ""));
        nvp.add(new BasicNameValuePair("sitting", lastSitting + ""));
        doSubmit("timeform", nvp, true);
        break;
    case R.id.med_cancel:

        Intent rIntent = new Intent(this, ReceiverAlarm.class);
        PendingIntent walkPendingIntent = PendingIntent.getBroadcast(context, 0, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent sitPendingIntent = PendingIntent.getBroadcast(context, 1, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        mAlarmMgr.cancel(walkPendingIntent);
        mAlarmMgr.cancel(sitPendingIntent);
        mNM.cancelAll();

        doSubmit("cancelform", nvp, true);
        break;
    case R.id.smily_button:
        if (smiliesShell.getVisibility() == View.GONE)
            smiliesShell.setVisibility(View.VISIBLE);
        else
            smiliesShell.setVisibility(View.GONE);
        break;
    case R.id.chat_text:
        smiliesShell.setVisibility(View.GONE);
        singleClick++;
        Handler handler = new Handler();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                singleClick = 0;
            }
        };

        if (singleClick == 1) {
            //Single click
            handler.postDelayed(r, 250);
        } else if (singleClick == 2) {
            //Double click
            singleClick = 0;
            ((EditText) findViewById(R.id.chat_text)).setText("");
        }
        break;
    case R.id.new_commit:
        Intent i = new Intent(this, ActivityCommit.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        break;
    default:
        smiliesShell.setVisibility(View.GONE);
        break;
    }
}

From source file:com.dudu.aios.ui.activity.MainRecordActivity.java

private void setWeatherAlarm() {
    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, WeatherAlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 20);
    mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 30 * 60 * 1000, pi);
}

From source file:arun.com.chromer.browsing.customtabs.CustomTabs.java

/**
 * Adds a menu item tapping which will minimize the current custom tab back to overview. This requires
 * merge tabs and apps and/*from ww  w.ja v  a2  s  .c  o m*/
 */
private void prepareMinimize() {
    if (!Preferences.get(activity).bottomBar() && Utils.ANDROID_LOLLIPOP) {
        final Intent minimizeIntent = new Intent(activity, MinimizeBroadcastReceiver.class);
        minimizeIntent.putExtra(EXTRA_KEY_ORIGINAL_URL, url);
        final PendingIntent pendingMin = PendingIntent.getBroadcast(activity, new Random().nextInt(),
                minimizeIntent, FLAG_UPDATE_CURRENT);
        builder.addMenuItem(activity.getString(R.string.minimize), pendingMin);
    }
}

From source file:com.heightechllc.breakify.MainActivity.java

/**
 * Starts the work or break timer/*  w w  w  . j a va  2  s.co m*/
 * @param duration The number of milliseconds to run the timer for. If currently paused, this
 *                 is the remaining time.
 */
@TargetApi(19)
private void startTimer(long duration) {
    // Stop blinking the time and state labels
    timeLbl.clearAnimation();
    stateLbl.clearAnimation();

    // Show the "Reset" and "Skip" btns
    resetBtn.setVisibility(View.VISIBLE);
    skipBtn.setVisibility(View.VISIBLE);

    // Update the start / stop label
    startStopLbl.setText(R.string.stop);
    startStopLbl.setVisibility(View.VISIBLE);

    if (timerState == TIMER_STATE_PAUSED && circleTimer.getTotalTime() > 0) {
        // We're resuming from a paused state, so calculate how much time is remaining, based
        //  on the total time set in the circleTimer
        circleTimer.setPassedTime(circleTimer.getTotalTime() - duration, false);
    } else {
        circleTimer.setTotalTime(duration);
        circleTimer.setPassedTime(0, false);
        circleTimer.updateTimeLbl(duration);
        // Record the total duration, so we can resume if the activity is destroyed
        sharedPref.edit().putLong("schedTotalTime", duration).apply();
    }

    circleTimer.startIntervalAnimation();

    timerState = TIMER_STATE_RUNNING;

    // Schedule the alarm to go off
    PendingIntent pi = PendingIntent.getBroadcast(this, ALARM_MANAGER_REQUEST_CODE,
            new Intent(this, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
    long ringTime = SystemClock.elapsedRealtime() + duration;
    if (Build.VERSION.SDK_INT >= 19) {
        // API 19 needs setExact()
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, ringTime, pi);
    } else {
        // APIs 1-18 use set()
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, ringTime, pi);
    }
    // Show the persistent notification
    AlarmNotifications.showUpcomingNotification(this, ringTime, getWorkState());

    // Record when the timer will ring and remove record of time remaining for the paused timer.
    // Save the scheduled ring time using Unix / epoch time, not elapsedRealtime, b/c that is
    //  reset on each boot.
    long timeFromNow = ringTime - SystemClock.elapsedRealtime();
    long ringUnixTime = System.currentTimeMillis() + timeFromNow;
    sharedPref.edit().putLong("schedRingTime", ringUnixTime).remove("pausedTimeRemaining").apply();
}

From source file:com.embeddedlog.LightUpDroid.timer.TimerReceiver.java

private void showTimesUpNotification(final Context context, TimerObj timerObj) {
    // Content Intent. When clicked will show the timer full screen
    PendingIntent contentIntent = PendingIntent.getActivity(context, timerObj.mTimerId,
            new Intent(context, TimerAlertFullScreen.class).putExtra(Timers.TIMER_INTENT_EXTRA,
                    timerObj.mTimerId),/*from w ww . jav a 2 s.  c  o m*/
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Add one minute action button
    PendingIntent addOneMinuteAction = PendingIntent.getBroadcast(context, timerObj.mTimerId,
            new Intent(Timers.NOTIF_TIMES_UP_PLUS_ONE).putExtra(Timers.TIMER_INTENT_EXTRA, timerObj.mTimerId),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Add stop/done action button
    PendingIntent stopAction = PendingIntent.getBroadcast(context, timerObj.mTimerId,
            new Intent(Timers.NOTIF_TIMES_UP_STOP).putExtra(Timers.TIMER_INTENT_EXTRA, timerObj.mTimerId),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Notification creation
    Notification notification = new Notification.Builder(context).setContentIntent(contentIntent)
            .addAction(R.drawable.ic_menu_add, context.getResources().getString(R.string.timer_plus_1_min),
                    addOneMinuteAction)
            .addAction(
                    timerObj.getDeleteAfterUse() ? android.R.drawable.ic_menu_close_clear_cancel
                            : R.drawable.ic_stop_normal,
                    timerObj.getDeleteAfterUse() ? context.getResources().getString(R.string.timer_done)
                            : context.getResources().getString(R.string.timer_stop),
                    stopAction)
            .setContentTitle(timerObj.getLabelOrDefault(context))
            .setContentText(context.getResources().getString(R.string.timer_times_up))
            .setSmallIcon(R.drawable.stat_notify_timer).setOngoing(true).setAutoCancel(false)
            .setPriority(Notification.PRIORITY_MAX).setDefaults(Notification.DEFAULT_LIGHTS).setWhen(0).build();

    // Send the notification using the timer's id to identify the
    // correct notification
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(timerObj.mTimerId,
            notification);
    if (Timers.LOGGING) {
        Log.v(TAG, "Setting times-up notification for " + timerObj.getLabelOrDefault(context) + " #"
                + timerObj.mTimerId);
    }
}

From source file:com.google.android.libraries.cast.companionlibrary.notification.VideoCastNotificationService.java

/**
 * Returns the {@link NotificationCompat.Action} for skipping to the next item in the queue. If
 * we are already at the end of the queue, we show a dimmed version of the icon for this action
 * and won't send any {@link PendingIntent}
 *///www  . j  a v a2 s .  c  om
protected NotificationCompat.Action getSkipNextAction() {
    PendingIntent pendingIntent = null;
    int iconResourceId = R.drawable.ic_notification_skip_next_semi_48dp;
    if (mHasNext) {
        Intent intent = new Intent(ACTION_PLAY_NEXT);
        intent.setPackage(getPackageName());
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        iconResourceId = R.drawable.ic_notification_skip_next_48dp;
    }

    return new NotificationCompat.Action.Builder(iconResourceId, getString(R.string.ccl_skip_next),
            pendingIntent).build();
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void mute(int alarmId) {
    Log.d(TAG, "mute()");

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) {
        Log.d(TAG, "mute() blocked - waiting for a location update");
        return;//from w  ww .  j  av a 2  s. c  om
    }

    // check if phone is already muted by the user
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
            && !Preferences.isMutingPeriod(preferences);
    if (isPhoneAlreadyMuted) {
        Log.d(TAG, "phone is already muted, scheduling next mute");
        scheduleMute(true);
        return;
    }

    // load the current period from the db
    MutingPeriod mutingPeriod = null;
    Log.d(TAG, "muting period id: " + alarmId);
    if (DEBUG_WITH_FAKE_ALARMS) {
        mutingPeriod = new MutingPeriod();
        mutingPeriod.setId(-1);
        mutingPeriod.setBegin(System.currentTimeMillis());
        mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000);
        mutingPeriod.setName("Fakeevent");
    } else {
        mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId);
    }

    // check if phone is located at university
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_started_locating));
    boolean isPhoneLocationKnown = false;
    boolean isPhoneLocatedAtUniversity = false;
    String locationSource = null;

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults());
        if (scanResult != null) {
            Log.d(TAG, "phone located by wifi: " + scanResult.SSID);
            isPhoneLocationKnown = true;
            isPhoneLocatedAtUniversity = true;
            locationSource = "wifi (" + scanResult.SSID + ")";
        }
    }

    if (!isPhoneLocationKnown) {
        // phone location could not be determined by wifi, trying network location instead...
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE")
                    .putExtra(EXTRA_ALARM_ID, alarmId);
            PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls)
            locationManager.removeUpdates(pendingLocationIntent);

            if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) {
                isPhoneLocationKnown = true;
                pendingLocationIntent.cancel();
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location == null) {
                    Log.d(TAG, "location received but still null");
                } else {
                    MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location);
                    if (mutingRegion != null) {
                        Log.d(TAG, "phone located by network @ " + mutingRegion.getName());
                        isPhoneLocatedAtUniversity = true;
                        locationSource = "location (" + mutingRegion.getName() + ")";
                    }
                }
            } else {
                Log.d(TAG, "trying to locate the phone by network...");
                // wait for a location update
                Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        pendingLocationIntent);
                return; // exit method - it will be re-called from the location broadcast receiver on a location update
            }
        }
    }

    boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences);

    if (isPhoneLocationKnown) {
        if (!isPhoneLocatedAtUniversity) {
            Log.d(TAG, "phone is not located at university, scheduling next mute");
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    } else {
        Log.d(TAG, "phone cannot be located");
        if (!isAlwaysMuteEnabled) {
            Log.d(TAG, "alwaysmute is disabled, scheduling next mute");
            Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE);
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    }

    // only turn the ringtone off if we aren't currently in a muting period.
    // if we are in a muting period the ringtone is already muted and the request should be ignored,
    // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true
    if (!Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOff(this);
    }

    // persist that from now on the phone is in a muting period
    Preferences.setMutingPeriod(preferences, true);

    // inform user via a notification that a course has started and the phone has been muted
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_muted));

    final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown;
    final String locationSourceAnalytics = locationSource;
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown",
            isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics);

    scheduleUnmute(mutingPeriod.getEnd());
}

From source file:cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.receiver.NotificationHelper.java

/**
 * Schedules to be woken up at the next notification time.
 *///  w ww  . ja  v  a 2 s.c o  m
private static void scheduleNext(Context context) {
    // Get first future notification
    final Calendar now = Calendar.getInstance();
    final List<cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.model.sql.Notification> notifications = cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.model.sql.Notification
            .getNotificationsWithTime(context, now.getTimeInMillis(), false);

    // if not empty, schedule alarm wake up
    if (!notifications.isEmpty()) {
        // at first's time
        // Create a new PendingIntent and add it to the AlarmManager
        Intent intent = new Intent(Intent.ACTION_RUN);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
        am.set(AlarmManager.RTC_WAKEUP, notifications.get(0).time, pendingIntent);
    }

    monitorUri(context);
}