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.android.development.Connectivity.java

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

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

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

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

From source file:com.hhunj.hhudata.ForegroundService.java

private void sendSMS(String message) {

    if (message == "")
        return;/*from  w  ww  .  j  av a  2  s  . c om*/

    //String stext  =  "  " +m_contactmap.size();

    //notification ,title
    showNotification("hhudata", message);

    if (m_alarmInWorktime) {//
        Date dt = new Date();
        if (IsDuringWorkHours(dt) == false) {
            return;
        } else {
            //alarm.

        }
    }

    if (message.length() > 140) {
        //....
        return;
    }

    // ---sends an SMS message to another device---
    SmsManager sms = SmsManager.getDefault();
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

    // create the sentIntent parameter
    Intent sentIntent = new Intent(SENT_SMS_ACTION);
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent, 0);

    // create the deilverIntent parameter
    Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
    PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);

    // register the Broadcast Receivers
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS sent success actions", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "SMS generic failure actions", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "SMS radio off failure actions", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "SMS null PDU failure actions", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }, new IntentFilter(SENT_SMS_ACTION));
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            Toast.makeText(getBaseContext(), "SMS delivered actions", Toast.LENGTH_SHORT).show();
        }
    }, new IntentFilter(DELIVERED_SMS_ACTION));

    // if message's length more than 70 ,
    // then call divideMessage to dive message into several part ,and call
    // sendTextMessage()
    // else direct call sendTextMessage()

    Iterator it = m_contactmap.keySet().iterator();
    while (it.hasNext()) {
        ContactColumn.ContactInfo info = m_contactmap.get(it.next());
        if (info.mobile == null)
            continue;
        String mobile = info.mobile.trim();
        if (mobile.length() >= 4) {
            if (message.length() > 70) {

                ArrayList<String> msgs = sms.divideMessage(message);
                for (String msg : msgs) {
                    sms.sendTextMessage(mobile, null, msg, sentPI, deliverPI);
                }
            } else {
                sms.sendTextMessage(mobile, null, message, sentPI, deliverPI);
            }
        }
    }

}

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

/**
 * Opposite of what {@link #prepareActionButton()} does. Fills a menu item with either secondary
 * browser or favorite share app./* ww w.  j  ava2  s  . c o  m*/
 */
private void preparePreferredAction() {
    assertBuilderInitialized();
    switch (Preferences.get(activity).preferredAction()) {
    case PREFERRED_ACTION_BROWSER:
        String pkg = Preferences.get(activity).favSharePackage();
        if (Utils.isPackageInstalled(activity, pkg)) {
            final String app = Utils.getAppNameWithPackage(activity, pkg);
            final String label = String.format(activity.getString(R.string.share_with), app);
            final Intent shareIntent = new Intent(activity, FavShareBroadcastReceiver.class);
            final PendingIntent pendingShareIntent = PendingIntent.getBroadcast(activity, 0, shareIntent,
                    FLAG_UPDATE_CURRENT);
            builder.addMenuItem(label, pendingShareIntent);
        }
        break;
    case PREFERRED_ACTION_FAV_SHARE:
        pkg = Preferences.get(activity).secondaryBrowserPackage();
        if (Utils.isPackageInstalled(activity, pkg)) {
            if (!pkg.equalsIgnoreCase(STABLE_PACKAGE)) {
                final String app = Utils.getAppNameWithPackage(activity, pkg);
                final String label = String.format(activity.getString(R.string.open_in_browser), app);
                final Intent browseIntent = new Intent(activity, SecondaryBrowserReceiver.class);
                final PendingIntent pendingBrowseIntent = PendingIntent.getBroadcast(activity, 0, browseIntent,
                        FLAG_UPDATE_CURRENT);
                builder.addMenuItem(label, pendingBrowseIntent);
            } else {
                Timber.d("Excluded secondary browser menu as it was Chrome");
            }
        }
        break;
    }
}

From source file:com.android.messaging.ui.UIIntentsImpl.java

@Override
public PendingIntent getPendingIntentForClearingNotifications(final Context context, final int updateTargets,
        final ConversationIdSet conversationIdSet, final int requestCode) {
    final Intent intent = new Intent(context, NotificationReceiver.class);
    intent.setAction(ACTION_RESET_NOTIFICATIONS);
    intent.putExtra(UI_INTENT_EXTRA_NOTIFICATIONS_UPDATE, updateTargets);
    if (conversationIdSet != null) {
        intent.putExtra(UI_INTENT_EXTRA_CONVERSATION_ID_SET, conversationIdSet.getDelimitedString());
    }/*from   ww w .ja v a 2 s  .  co  m*/
    return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

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

/**
 * Returns the {@link NotificationCompat.Action} for skipping to the previous item in the queue.
 * If we are already at the beginning of the queue, we show a dimmed version of the icon for
 * this action and won't send any {@link PendingIntent}
 *///ww w  . jav  a2 s .  c o m
protected NotificationCompat.Action getSkipPreviousAction() {
    PendingIntent pendingIntent = null;
    int iconResourceId = R.drawable.ic_notification_skip_prev_semi_48dp;
    if (mHasPrev) {
        Intent intent = new Intent(ACTION_PLAY_PREV);
        intent.setPackage(getPackageName());
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        iconResourceId = R.drawable.ic_notification_skip_prev_48dp;
    }

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

From source file:org.kaoriha.phonegap.plugins.releasenotification.Notifier.java

private void schedule(long after) {
    Intent intent = new Intent(ctx, Receiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + after, pi);
}

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

/**
 * ??//w  w w. j a  va  2  s . com
 */
@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.google.android.apps.paco.NotificationCreator.java

private void createAlarmForSnooze(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    Experiment experiment = experimentProviderUtil.getExperiment(notificationHolder.getExperimentId());
    Integer snoozeTime = experiment.getSignalingMechanisms().get(0).getSnoozeTime();
    int snoozeMinutes = snoozeTime / MILLIS_IN_MINUTE;
    DateTime timeoutMinutes = new DateTime(alarmTime).plusMinutes(snoozeMinutes);
    long snoozeDurationInMillis = timeoutMinutes.getMillis();

    Log.i(PacoConstants.TAG,/* w ww.j a  v  a2  s . c  om*/
            "Creating snooze alarm to resound notification for holder: " + notificationHolder.getId()
                    + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
                    + new DateTime(alarmTime).toString() + " waking up from snooze in " + timeoutMinutes
                    + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());
    ultimateIntent.putExtra(SNOOZE_REPEATER_EXTRA_KEY, true);

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 3, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(intent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, snoozeDurationInMillis, intent);
}

From source file:com.andrew.apolloMod.service.ApolloService.java

@SuppressLint({ "WorldWriteableFiles", "WorldReadableFiles" })
@Override//  ww w .ja  va 2s  .  c  om
public void onCreate() {
    super.onCreate();

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(rec);
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(rec);
    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    if (Constants.isApi14Supported()) {
        mRemoteControlClient = new RemoteControlClient(mediaPendingIntent);
        mAudioManager.registerRemoteControlClient(mRemoteControlClient);

        int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
        mRemoteControlClient.setTransportControlFlags(flags);
    }

    mPreferences = getSharedPreferences(APOLLO_PREFERENCES, MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();

    // Needs to be done in this thread, since otherwise
    // ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer();
    mPlayer.setHandler(mMediaplayerHandler);

    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    commandFilter.addAction(CYCLEREPEAT_ACTION);
    commandFilter.addAction(TOGGLESHUFFLE_ACTION);
    registerReceiver(mIntentReceiver, commandFilter);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that
    // case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}

From source file:goo.TeaTimer.TimerActivity.java

/**
 * Starts the timer at the given time//  www  .  ja  v a2 s.c  om
 * @param time with which to count down
 * @param service whether or not to start the service as well
 */
private void timerStart(int time, boolean service) {
    if (LOG)
        Log.v(TAG, "Starting the timer...");

    // Star external service
    enterState(RUNNING);

    if (service) {
        if (LOG)
            Log.v(TAG, "Starting the timer service ...");
        Intent intent = new Intent(getApplicationContext(), TimerReceiver.class);
        intent.putExtra("SetTime", mLastTime);
        mPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        mAlarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + time,
                mPendingIntent);
    }

    // Internal thread to properly update the GUI
    mTimer = new Timer();
    mTime = time;
    mTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            timerTic();
        }
    }, 0, TIMER_TIC);

    aquireWakeLock();
}