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.chess.genesis.net.GenesisNotifier.java

private static void CancelWakup(final Context context) {
    final Intent intent = new Intent(context, GenesisAlarm.class);
    final PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pintent);// w  w w  .j  a  v  a 2  s. c o m
}

From source file:damo.three.ie.prepay.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    try {/*from www. j av  a  2 s.co  m*/
        Log.d(Constants.TAG, "Fetching usages from service.");
        UsageFetcher usageFetcher = new UsageFetcher(context, true);
        JSONArray usages = usageFetcher.getUsages();

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences sharedUsagePref = context.getSharedPreferences("damo.three.ie.previous_usage",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedUsagePref.edit();
        editor.putLong("last_refreshed_milliseconds", new DateTime().getMillis());
        editor.putString("usage_info", usages.toString());
        editor.commit();

        // Register alarms for newly refreshed usages in background
        boolean notificationsEnabled = sharedPref.getBoolean("notification", true);
        List<UsageItem> usageItems = JSONUtils.jsonToUsageItems(usages);
        List<BasicUsageItem> basicUsageItems = UsageUtils.getAllBasicItems(usageItems);
        UsageUtils.registerInternetExpireAlarm(context, basicUsageItems, notificationsEnabled, true);

    } catch (Exception e) {
        // Try again at 7pm, unless its past 7pm. Then forget and let tomorrow's alarm do the updating.
        // Still trying to decide if I need a more robust retry mechanism.
        Log.d(Constants.TAG, "Caught exception: " + e.getLocalizedMessage());
        Calendar calendar = Calendar.getInstance();
        if (calendar.get(Calendar.HOUR_OF_DAY) < Constants.HOUR_TO_RETRY) {
            Log.d(Constants.TAG, "Scheduling a re-try for 7pm");
            calendar.set(Calendar.HOUR_OF_DAY, Constants.HOUR_TO_RETRY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            Intent receiver = new Intent(context, UpdateReceiver.class);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // Using different request code to 0 so it won't conflict with other alarm below.
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 3, receiver,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Keeping efficiency in mind:
            // http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME
            am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
        }
    } finally {
        Log.d(Constants.TAG, "Finish UpdateService");
        UpdateReceiver.completeWakefulIntent(intent);
    }
}

From source file:com.google.android.apps.muzei.NewWallpaperNotificationReceiver.java

public static void maybeShowNewArtworkNotification(Context context, Artwork artwork,
        BitmapRegionLoader bitmapRegionLoader) {
    if (artwork == null || artwork.getImageUri() == null || bitmapRegionLoader == null) {
        return;//from ww  w.ja va  2s. c o  m
    }

    ArtDetailOpenedClosedEvent adoce = EventBus.getDefault().getStickyEvent(ArtDetailOpenedClosedEvent.class);
    if (adoce != null && adoce.isArtDetailOpened()) {
        return;
    }

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (!sp.getBoolean(PREF_ENABLED, true)) {
        return;
    }

    String lastSeenImageUri = sp.getString(PREF_LAST_SEEN_NOTIFICATION_IMAGE_URI, null);
    if (TextUtils.equals(lastSeenImageUri, artwork.getImageUri().toString())) {
        return;
    }

    Rect rect = new Rect();
    int width = bitmapRegionLoader.getWidth();
    int height = bitmapRegionLoader.getHeight();
    if (width > height) {
        rect.set((width - height) / 2, 0, (width + height) / 2, height);
    } else {
        rect.set(0, (height - width) / 2, width, (height + width) / 2);
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = ImageUtil.calculateSampleSize(height, 256);
    Bitmap largeIcon = bitmapRegionLoader.decodeRegion(rect, options);

    NotificationCompat.Builder nb = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_stat_muzei).setPriority(Notification.PRIORITY_MIN).setAutoCancel(true)
            .setContentTitle(artwork.getTitle())
            .setContentText(context.getString(R.string.notification_new_wallpaper)).setLargeIcon(largeIcon)
            .setContentIntent(PendingIntent.getActivity(context, 0,
                    Intent.makeMainActivity(new ComponentName(context, MuzeiActivity.class)),
                    PendingIntent.FLAG_UPDATE_CURRENT))
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0,
                    new Intent(context, NewWallpaperNotificationReceiver.class)
                            .setAction(ACTION_MARK_NOTIFICATION_READ),
                    PendingIntent.FLAG_UPDATE_CURRENT));
    NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle(nb).bigLargeIcon(null)
            .setBigContentTitle(artwork.getTitle()).setSummaryText(artwork.getByline()).bigPicture(largeIcon);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, style.build());

    // Clear any last-seen notification
    sp.edit().remove(PREF_LAST_SEEN_NOTIFICATION_IMAGE_URI).apply();
}

From source file:com.benext.thibault.appsample.notification.builder.NotificationBuilder.java

private static ArrayList<android.support.v4.app.NotificationCompat.Action> getActionsSample(Context context) {
    ArrayList<NotificationCompat.Action> actions = new ArrayList<>();

    //User click on action triggers broadcast which is received by WearActionReceiver.class
    //Put notification id and flag WEAR_ACTION.
    //Using these parameters WearActionReceiver.class will know which action was clicked
    Intent notifyNextTimeIntent = new Intent(context, WearActionReceiver.class);
    notifyNextTimeIntent.putExtra(WearActionReceiver.NOTIFICATION_ID_STRING, NOTIFICATION_ID);
    notifyNextTimeIntent.putExtra(WearActionReceiver.WEAR_ACTION, WearActionReceiver.SNOOZE_NOTIFICATION);

    PendingIntent pendingIntentNotify = PendingIntent.getBroadcast(context, WEAR_REQUEST_CODE,
            notifyNextTimeIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    //text shown in notification
    String notifyAgainText = context.getString(R.string.notification_next_in_line);

    //Wear action - this action will be shown only on Android Wear devices
    //Set action icon, text and pending intent which will be executed on click
    //When user clicks on this icon he will "snooze" notification
    actions.add(/* w  w  w.  j a v a 2s  .  c  om*/
            new NotificationCompat.Action.Builder(R.drawable.resto_icn, notifyAgainText, pendingIntentNotify)
                    .build());

    return actions;
}

From source file:com.b44t.messenger.MusicPlayerService.java

@SuppressLint("NewApi")
@Override//from   w  ww  .  j av  a2s .  com
public int onStartCommand(Intent intent, int flags, int startId) {
    try {
        MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
        if (messageObject == null) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            });
            return START_STICKY;
        }
        if (supportLockScreenControls) {
            ComponentName remoteComponentName = new ComponentName(getApplicationContext(),
                    MusicPlayerReceiver.class.getName());
            try {
                if (remoteControlClient == null) {
                    audioManager.registerMediaButtonEventReceiver(remoteComponentName);
                    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                    mediaButtonIntent.setComponent(remoteComponentName);
                    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent,
                            0);
                    remoteControlClient = new RemoteControlClient(mediaPendingIntent);
                    audioManager.registerRemoteControlClient(remoteControlClient);
                }
                remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                        | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                        | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
            } catch (Exception e) {
                FileLog.e("messenger", e);
            }
        }
        createNotification(messageObject);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return START_STICKY;
}

From source file:emcewen.websms.services.C2DMRegistrationService.java

private void registerToC2dm() {
    Log.d(TAG, "Registering with C2DM");
    // create a C2DM registration intent
    Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    // add to it our application's "signature"
    registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    // role email that our app server will use
    // later to authenticate before it can use C2DM
    registrationIntent.putExtra("sender", "sdnotifications@gmail.com");
    // request C2DM registration (async operation)
    super.startService(registrationIntent);
}

From source file:com.finchuk.clock2.alarms.background.UpcomingAlarmReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
    // Unmarshall the bytes into a parcel and create our Alarm with it.
    final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
    if (alarm == null) {
        throw new IllegalStateException("No alarm received");
    }/*from   w  w  w .ja va2 s .c  o m*/

    final long id = alarm.getId();
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
    if (intent.getAction() == null || actionShowSnoozing) {
        // Prepare notification
        // http://stackoverflow.com/a/15803726/5055032
        // Notifications aren't updated on the UI thread, so we could have
        // done this in the background. However, no lengthy operations are
        // done here, so doing so is a premature optimization.
        String title;
        String text;
        if (actionShowSnoozing) {
            if (!alarm.isSnoozed()) {
                throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
            }
            title = alarm.label().isEmpty() ? context.getString(R.string.alarm) : alarm.label();
            text = context.getString(R.string.title_snoozing_until,
                    TimeFormatUtils.formatTime(context, alarm.snoozingUntil()));
        } else {
            // No intent action required for default behavior
            title = context.getString(R.string.upcoming_alarm);
            text = TimeFormatUtils.formatTime(context, alarm.ringsAt());
            if (!alarm.label().isEmpty()) {
                text = alarm.label() + ", " + text;
            }
        }

        Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class).setAction(ACTION_DISMISS_NOW)
                .putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
        PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id, dismissIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification note = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_alarm_24dp)
                .setContentTitle(title).setContentText(text)
                .setContentIntent(ContentIntentUtils.create(context, MainActivity.PAGE_ALARMS, id))
                .addAction(R.drawable.ic_dismiss_alarm_24dp, context.getString(R.string.dismiss_now), piDismiss)
                .build();
        nm.notify(TAG, (int) id, note);
    } else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
        nm.cancel(TAG, (int) id);
    } else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
        new AlarmController(context, null).cancelAlarm(alarm, false, true);
    }
}

From source file:com.appsaur.tarucassist.AlarmReceiver.java

public void setAlarm(Context context, Calendar calendar, int ID) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BaseActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using notification time
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:com.nfc.gemkey.MainActivity.java

@Override
public void onCreate(Bundle icicle) {
    if (DEBUG)/*from   w  w w.  j a  va  2s.c o  m*/
        Log.d(TAG, "onCreate");
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);

    mAdapter = NfcAdapter.getDefaultAdapter(this);

    // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
    // will fill in the intent with the details of the discovered tag before delivering to
    // this activity.
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Setup an intent filter for all MIME based dispatches
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    mFilters = new IntentFilter[] { tagDetected };

    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, filter);

    if (getLastNonConfigurationInstance() != null) {
        Log.i(TAG, "open usb accessory@onCreate");
        mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
        openAccessory(mAccessory);
    }

    buttonLED = (ToggleButton) findViewById(R.id.nfc_btn);
    buttonLED.setBackgroundResource(
            buttonLED.isChecked() ? R.drawable.btn_toggle_yes : R.drawable.btn_toggle_no);
    buttonLED.setOnCheckedChangeListener(mKeyLockListener);

    tagId = (TextView) findViewById(R.id.nfc_tag);
    tagId.setText(R.string.nfc_scan_tag);

    // Avoid NetworkOnMainThreadException
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
            .detectNetwork().penaltyLog().build());

    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
            .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:de.incoherent.suseconferenceclient.tasks.CheckForUpdatesTask.java

@Override
protected Long doInBackground(Void... params) {
    String kUrl = "https://conference.opensuse.org/osem/api/v1/conferences/gRNyOIsTbvCfJY5ENYovBA";
    if (kUrl.length() <= 0)
        return 0l;

    String updatesUrl = mConference.getUrl() + "/updates.json";
    int lastUpdateRevision = mDb.getLastUpdateValue(mConference.getSqlId());
    int revisionLevel = lastUpdateRevision;

    try {//  w ww  . j  a va 2 s  .  c o  m
        JSONObject updateReply = HTTPWrapper.get(updatesUrl);
        if (updateReply == null)
            return 0l;
        int newLevel = updateReply.getInt("revision");
        if (newLevel > revisionLevel) {
            long id = mConference.getSqlId();
            // Cache favorites and alerts
            List<String> favoriteGuids = mDb.getFavoriteGuids(id);
            List<Event> alerts = mDb.getAlertEvents(id);
            List<String> alertGuids = new ArrayList<String>();
            // Now cancel all of the outstanding alerts, in case
            // a talk has been moved
            AlarmManager manager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            for (Event e : alerts) {
                alertGuids.add("\"" + e.getGuid() + "\"");
                Log.d("SUSEConferences", "Removing an alert for " + e.getTitle());

                Intent intent = new Intent(mContext, AlarmReceiver.class);
                intent.putExtras(ScheduleDetailsActivity.generateAlarmIntentBundle(mContext, e));
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
                        intent.getStringExtra("intentId").hashCode(), intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                manager.cancel(pendingIntent);
                pendingIntent.cancel();
            }

            // Now clear the DB
            mDb.clearDatabase(id);
            // Download schedule
            ConferenceCacher cacher = new ConferenceCacher(new ConferenceCacherProgressListener() {
                @Override
                public void progress(String progress) {
                    publishProgress(progress);
                }
            });

            long val = cacher.cacheConference(mConference, mDb);
            mErrorMessage = cacher.getLastError();
            if (val == -1) {
                mDb.setConferenceAsCached(id, 0);
            } else {
                mDb.setLastUpdateValue(id, newLevel);
                mDb.toggleEventsInMySchedule(favoriteGuids);
                mDb.toggleEventAlerts(alertGuids);
                alerts = mDb.getAlertEvents(id);
                // ... And re-create the alerts, if they are in the future
                Date currentDate = new Date();
                for (Event e : alerts) {
                    if (currentDate.after(e.getDate()))
                        continue;
                    Log.d("SUSEConferences", "Adding an alert for " + e.getTitle());
                    alertGuids.add("\"" + e.getGuid() + "\"");
                    Intent intent = new Intent(mContext, AlarmReceiver.class);
                    intent.putExtras(ScheduleDetailsActivity.generateAlarmIntentBundle(mContext, e));
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
                            intent.getStringExtra("intentId").hashCode(), intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    manager.set(AlarmManager.RTC_WAKEUP, e.getDate().getTime() - 300000, pendingIntent);
                }

            }
            return val;
        } else {
            return 0l;
        }
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}