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.jay.pea.mhealthapp2.utilityClasses.AlarmReceiver.java

public void setOnetimeTimer(Context context) {
    Log.d(TAG, "set on time timer");
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.TRUE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);

}

From source file:com.awt.supark.ParkingTimerService.java

private void createNotification(final int id, final String licenseNum, final String formattedEndTime,
        final long remainingTime, final long parkedTime, final long parkedUntil, boolean alert) {
    try {//from   w w  w  .j ava2s  .  c o  m
        // Cancel button action
        Intent cancelIntent = new Intent(ACTION_CANCEL);
        cancelIntent.putExtra("cancelId", id);
        PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, id, cancelIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        // Renew button action
        Intent renewIntent = new Intent(ACTION_RENEW);
        renewIntent.putExtra("renewId", id);
        PendingIntent pIntentRenew = PendingIntent.getBroadcast(this, id, renewIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        mNotification = new NotificationCompat.Builder(getApplicationContext()); // Setting the notification parameters:
        mNotification.setSmallIcon(R.mipmap.ic_directions_car_white_24dp); // * icon
        mNotification.setOngoing(true); // * making it ongoing so the user can't swipe away
        mNotification.setContentTitle(
                getResources().getString(R.string.parking_status_of) + " " + licenseNum.toUpperCase()); // * title
        mNotification.setContentText(
                remainingTime + " " + getResources().getString(R.string.minutes_left) + " " + formattedEndTime); // * content text
        mNotification.setProgress((int) (parkedUntil - parkedTime), (int) remainingTime * 60, false); // * progress bar to visualize the remaining time
        mNotification.addAction(R.mipmap.ic_highlight_off_white_24dp, getResources().getString(R.string.cancel),
                pIntentCancel); // * cancel button

        // Playing alert if the alerts are turned on
        if (alert && sharedPreferences.getBoolean("alertBefore", true)) {
            mNotification.setSound(soundUri);
            mNotification.setLights(Color.RED, 3000, 3000);
            mNotification.setVibrate(new long[] { 1000, 1000 });
        }

        notificationManager.notify(id, mNotification.build()); // Finally we can build the actual notification where the ID is the selected car's ID

    } catch (Exception e) {
        Log.i("Service", "Failed to create notification for ID: " + id);
        Log.i("Service", "Exception: " + e.toString());
    }
}

From source file:no.ntnu.idi.socialhitchhiking.SocialHitchhikingApplication.java

/**
 * Starts a service that will poll the server for updates at a regular time interval.
 * It will start 10 sec after the app is started, then poll according to the update interval 
 * chosen in settings. //w  ww.  j  a  v  a2 s  .c om
 */
public void startService() {
    Intent intent = new Intent(this, AlarmService.class);
    service = PendingIntent.getBroadcast(this, 0, intent, 0);
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 10 * 1000;
    am.cancel(service);

    int interval = Integer.valueOf(getSettings().getUpdateInterval());
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval * 1000, service);
    keyMap.put("alarmService", true);
}

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

/**
 * Turns OFF automatic ringtone muting during courses.
 *//*from   w ww  . j a v a 2s . c o m*/
private void turnOff() {
    Log.d(TAG, "turnOff()");
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_OFF);

    // if the phone is currently in a muting period, turn the ringtone back on before turning off the service
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOn(this);
        Preferences.setMutingPeriod(preferences, false);
    }

    // remove eventually existing user notification
    removeNotification(Studentportal.NOTIFICATION_MS_INFO);

    // cancel an eventually existing pending alarm and the beloging intent as well (otherwise isRunning would always return true)
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, OnAlarmReceiver.class).putExtra(ACTION, ACTION_NONE);
    PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.cancel(pendingAlarmIntent);
    pendingAlarmIntent.cancel();

    // cancel an eventually exisiting location broadcast receiver
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE");
    PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    locationManager.removeUpdates(pendingLocationIntent);
    pendingLocationIntent.cancel();

    if (isRunning()) {
        Log.e(TAG, "COULD NOT TURN OFF");
    }
}

From source file:ca.mudar.snoozy.receiver.PowerConnectionReceiver.java

private void notify(Context context, boolean isConnectedPower, boolean hasVibration, boolean hasSound,
        int notifyCount) {
    final Resources res = context.getResources();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentTitle(res.getString(R.string.notify_content_title))
            .setAutoCancel(true);/*from   ww w .  j av  a 2  s  .  c  o m*/

    if (notifyCount == 1) {
        final int resContentTextSingle = (isConnectedPower ? R.string.notify_content_text_single_on
                : R.string.notify_content_text_single_off);
        mBuilder.setContentText(res.getString(resContentTextSingle));
    } else {
        mBuilder.setNumber(notifyCount).setContentText(res.getString(R.string.notify_content_text_multi));
    }

    if (hasVibration && hasSound) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
    } else if (hasVibration) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    } else if (hasSound) {
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    }

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, MainActivity.class);
    final Bundle extras = new Bundle();
    extras.putBoolean(Const.IntentExtras.INCREMENT_NOTIFY_GROUP, true);
    extras.putBoolean(Const.IntentExtras.RESET_NOTIFY_NUMBER, true);
    resultIntent.putExtras(extras);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    mBuilder.setContentIntent(
            PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    Intent receiverIntent = new Intent(context, PowerConnectionReceiver.class);
    receiverIntent.setAction(Const.IntentActions.NOTIFY_DELETE);
    PendingIntent deleteIntent = PendingIntent.getBroadcast(context, Const.RequestCodes.RESET_NOTIFY_NUMBER,
            receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setDeleteIntent(deleteIntent);

    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // NOTIFY_ID allows updates to the notification later on.
    mNotificationManager.notify(Const.NOTIFY_ID, mBuilder.build());
}

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 w ww  . j a  v  a 2s. c  om
    }

    // 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:com.dwdesign.tweetings.app.TweetingsApplication.java

public void register(View view) {
    final String consumer_key = mPreferences.getString(PREFERENCE_KEY_CONSUMER_KEY, null);
    final String consumer_secret = mPreferences.getString(PREFERENCE_KEY_CONSUMER_SECRET, null);

    if (isNullOrEmpty(consumer_key) || isNullOrEmpty(consumer_secret)) {
        Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
        intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
        intent.putExtra("sender", C2DM_SENDER);
        startService(intent);/*  w  w  w.  ja  va  2 s. c  om*/
    }
}

From source file:com.inovex.zabbixmobile.push.NotificationService.java

private void createNotification(String status, String message, Long triggerid) {
    int notIcon;/*  w  ww .j a v a2 s .  c o m*/
    if (status != null && status.equals("OK")) {
        notIcon = R.drawable.ok;
    } else if (status != null && status.equals("PROBLEM")) {
        notIcon = R.drawable.problem;
    } else {
        notIcon = R.drawable.icon;
    }
    String tickerMessage;
    if (message != null && message.length() > 0) {
        tickerMessage = message;
    } else {
        return; // there is obviously no sensable message here
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(NotificationService.this);
    notificationBuilder.setTicker(tickerMessage);
    notificationBuilder.setWhen(System.currentTimeMillis());

    if (oldNotificationIcons) {
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
        notificationBuilder.setSmallIcon(notIcon);
    } else {
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), notIcon));
        notificationBuilder.setSmallIcon(R.drawable.icon);
    }

    // we do not start MainActivity directly, but
    // send a
    // broadcast which will be received by a
    // NotificationBroadcastReceiver which resets
    // the
    // notification status and starts MainActivity.
    Intent notificationIntent = new Intent();
    notificationIntent.setAction(ACTION_ZABBIX_NOTIFICATION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(NotificationService.this, uniqueRequestCode(),
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    notificationBuilder.setContentTitle(getResources().getString(R.string.notification_title));
    notificationBuilder.setContentText(message);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationBuilder.setNumber(++numNotifications);

    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setOnlyAlertOnce(false);

    if (previousMessages.size() == NUM_STACKED_NOTIFICATIONS)
        previousMessages.poll();
    previousMessages.offer(message);
    // if there are several notifications, we stack
    // them in the
    // extended view
    if (numNotifications > 1) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        // Sets a title for the Inbox style big view
        inboxStyle.setBigContentTitle(getResources().getString(R.string.notification_title));
        // Moves events into the big view
        for (CharSequence prevMessage : previousMessages) {
            inboxStyle.addLine(prevMessage);
        }
        if (numNotifications > NUM_STACKED_NOTIFICATIONS) {
            inboxStyle.setSummaryText((numNotifications - NUM_STACKED_NOTIFICATIONS) + " more");
        }
        // Moves the big view style object into the
        // notification
        // object.
        notificationBuilder.setStyle(inboxStyle);
    }

    if (status != null && status.equals("OK")) {
        if (okRingtone != null) {
            notificationBuilder.setSound(Uri.parse(okRingtone));
        }
    } else {
        if (ringtone != null) {
            notificationBuilder.setSound(Uri.parse(ringtone));
        }
    }

    Notification notification = notificationBuilder.build();

    Intent notificationDeleteIntent = new Intent();
    notificationDeleteIntent.setAction(ACTION_ZABBIX_NOTIFICATION_DELETE);
    notification.deleteIntent = PendingIntent.getBroadcast(NotificationService.this, 0,
            notificationDeleteIntent, 0);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // We use the same ID because we want to stack
    // the notifications and we don't really care
    // about the trigger ID anyway (clicking the
    // notification just starts the main activity).
    mNotificationManager.notify(0, notification);
}

From source file:com.google.android.gcm.GCMRegistrar.java

public static synchronized void internalRegister(Context context, String... senderIds) {
    if (senderIds == null || senderIds.length == 0) {
        throw new IllegalArgumentException("No senderIds");
    }/*  ww  w  .  j  a v  a  2  s  .co m*/
    StringBuilder builder = new StringBuilder(senderIds[0]);
    for (int i = 1; i < senderIds.length; i++) {
        builder.append(',').append(senderIds[i]);
    }
    String senders = builder.toString();
    Log.v(TAG, "Registering app " + context.getPackageName() + " of senders " + senders);
    Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
    intent.setPackage(GSF_PACKAGE);
    intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
            PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    intent.putExtra(GCMConstants.EXTRA_SENDER, senders);
    context.startService(intent);
}

From source file:com.audiokernel.euphonyrmt.service.NotificationHandler.java

/**
 * Build a pending intent for use with the notification button controls.
 *
 * @param action The ACTION intent string.
 * @return The pending intent.//from   www .j  a v  a 2 s  .co  m
 */
private PendingIntent buildPendingIntent(final String action) {
    final Intent intent = new Intent(mServiceContext, RemoteControlReceiver.class);
    intent.setAction(action);
    return PendingIntent.getBroadcast(mServiceContext, 0, intent, 0);
}