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

public void registerPush() {
    //Log.w("C2DM", "start registration process");
    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);//from  ww  w . j  a v a  2 s.co  m
    }
}

From source file:com.example.android.notifyme.MainActivity.java

/**
 * OnClick method for the "Update Me!" button. Updates the existing notification to show a
 * picture.// w  w w  .  j a v a 2s  . co m
 */
private void updateNotification() {

    //Load the drawable resource into the a bitmap image
    Bitmap androidImage = BitmapFactory.decodeResource(getResources(), R.drawable.mascot_1);

    //Sets up the pending intent that is delivered when the notification is clicked
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Sets up the pending intent to cancel the notification,
    // delivered when the user dismisses the notification
    Intent cancelIntent = new Intent(ACTION_CANCEL_NOTIFICATION);
    PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, cancelIntent,
            PendingIntent.FLAG_ONE_SHOT);

    //Sets up the pending intent associated with the Learn More notification action,
    //uses an implicit intent to go to the web.
    Intent learnMoreIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(NOTIFICATION_GUIDE_URL));
    PendingIntent learnMorePendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, learnMoreIntent,
            PendingIntent.FLAG_ONE_SHOT);

    //Build the updated notification
    NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.notification_title))
            .setContentText(getString(R.string.notification_text)).setSmallIcon(R.drawable.ic_android)
            .setContentIntent(notificationPendingIntent).setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setDefaults(NotificationCompat.DEFAULT_ALL).setDeleteIntent(cancelPendingIntent)
            .addAction(R.drawable.ic_learn_more, getString(R.string.learn_more), learnMorePendingIntent)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(androidImage)
                    .setBigContentTitle(getString(R.string.notification_updated)));

    //Disable the update button, leaving only the option to cancel
    mNotifyButton.setEnabled(false);
    mUpdateButton.setEnabled(false);
    mCancelButton.setEnabled(true);

    //Deliver the notification
    Notification myNotification = notifyBuilder.build();
    mNotifyManager.notify(NOTIFICATION_ID, myNotification);

}

From source file:com.ekumen.tangobot.application.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

    // Load raw resources
    for (Pair<Integer, String> ip : mResourcesToLoad) {
        mOpenedResources.add(new ParameterLoaderNode.Resource(
                getResources().openRawResource(ip.first.intValue()), ip.second));
    }//from   w  w  w .ja  v a  2s. co  m

    mSharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // UI
    initializeUI();

    // USB handling code
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mUsbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    mUsbAttachedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mLog.info("Received USB Intent");
            if (intent.getAction() == ACTION_USB_PERMISSION
                    && intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                onDeviceReady((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
            }
        }
    };
    mUsbDetachedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mLog.info("Received USB disconnection Intent");
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            onDeviceDetached(device);
        }
    };
}

From source file:com.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java

/**
 * Starts the alarm repeater after a disconnection from a WiFi network.
 * The alarm is firing request to discover server at regular time interval
 * //from   w w w .j a  v a2s  .c  o m
 * @param context The context to use
 * @return true on success
 */
private boolean startAlarmRepeater(Context context) {

    boolean returnValue = false;

    // Gets the Binder to the DiscoverServerService
    IBinder b = peekService(context, new Intent(context, DiscoverServerService.class));
    DiscoverServerApi discoverServerApi = DiscoverServerApi.Stub.asInterface(b);

    // start the alarm repeater only if the api exists and the discover process in not running
    try {
        if (b != null && discoverServerApi != null && !discoverServerApi.isRunning()) {
            // Get the alarm manager
            if (alarmManager == null)
                alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // Instantiate the intent and set its action
            Intent i = new Intent(context, this.getClass());
            i.setAction(context.getResources().getString(R.string.broadcast_startdiscovery));
            // send the wifiBroadcastAddress together with the intent
            i.putExtra("wifiBroadcastAddress", wifiBroadcastAddress);
            // Get the broadcast
            PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (pending != null) {
                Calendar cal = Calendar.getInstance();
                // cancel the alarm
                alarmManager.cancel(pending);
                // Run the intent immediately and schedule repeating at fixed time intervals
                context.sendBroadcast(i);
                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                        cal.getTimeInMillis() + DroidDrinViewerConstants.DISCOVER_REPEAT_TIME,
                        DroidDrinViewerConstants.DISCOVER_REPEAT_TIME, pending);
                returnValue = true;
            }
        }
    } catch (RemoteException e) {
        e.printStackTrace();
        returnValue = false;
    }
    return returnValue;
}

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

public static 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 notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.alarm_missed_title))
            .setContentText(instance.mLabel.isEmpty() ? alarmTime
                    : context.getString(R.string.alarm_missed_text, alarmTime, label))
            .setSmallIcon(R.drawable.stat_notify_alarm).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);/*from w  ww  .  ja v a 2s. c o  m*/

    final int hashCode = instance.hashCode();

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

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

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(hashCode, notification.build());
}

From source file:com.onesignal.GenerateNotification.java

private static PendingIntent getNewActionPendingIntent(int requestCode, Intent intent) {
    if (openerIsBroadcast)
        return PendingIntent.getBroadcast(currentContext, requestCode, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    return PendingIntent.getActivity(currentContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:at.maui.cheapcast.service.CheapCastService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand()");

    Notification n = null;/*ww  w .  j  a v  a 2s. c o m*/
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        Notification.Builder mBuilder = new Notification.Builder(this).setSmallIcon(R.drawable.ic_service)
                .setContentTitle("CheapCast").setContentText("Service enabled.").setOngoing(true)
                .addAction(R.drawable.ic_reload, getString(R.string.restart_service),
                        PendingIntent.getBroadcast(this, 1, new Intent(Const.ACTION_RESTART),
                                PendingIntent.FLAG_ONE_SHOT))
                .addAction(R.drawable.ic_stop, getString(R.string.stop_service), PendingIntent
                        .getBroadcast(this, 2, new Intent(Const.ACTION_STOP), PendingIntent.FLAG_ONE_SHOT));

        Intent i = new Intent(this, PreferenceActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
        mBuilder.setContentIntent(pi);
        n = mBuilder.build();
    } else {
        Intent i = new Intent(this, PreferenceActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_service).setContentTitle("CheapCast")
                .setContentText("Service enabled.").setOngoing(true).setContentIntent(pi);
        n = mBuilder.getNotification();
    }

    startForeground(1337, n);

    if (!mRunning)
        initService();

    return START_STICKY;
}

From source file:com.bluros.updater.service.UpdateCheckService.java

private void recordAvailableUpdates(LinkedList<UpdateInfo> availableUpdates, Intent finishedIntent) {

    if (availableUpdates == null) {
        sendBroadcast(finishedIntent);//from  ww w. ja va 2s.  c  om
        return;
    }

    // Store the last update check time and ensure boot check completed is true
    Date d = new Date();
    PreferenceManager.getDefaultSharedPreferences(UpdateCheckService.this).edit()
            .putLong(Constants.LAST_UPDATE_CHECK_PREF, d.getTime())
            .putBoolean(Constants.BOOT_CHECK_COMPLETED, true).apply();

    int realUpdateCount = finishedIntent.getIntExtra(EXTRA_REAL_UPDATE_COUNT, 0);
    UpdateApplication app = (UpdateApplication) getApplicationContext();

    // Write to log
    Log.i(TAG, "The update check successfully completed at " + d + " and found " + availableUpdates.size()
            + " updates (" + realUpdateCount + " newer than installed)");

    if (realUpdateCount != 0 && !app.isMainActivityActive()) {
        // There are updates available
        // The notification should launch the main app
        Intent i = new Intent(this, UpdatesSettings.class);
        i.putExtra(UpdatesSettings.EXTRA_UPDATE_LIST_UPDATED, true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);

        Resources res = getResources();
        String text = res.getQuantityString(R.plurals.not_new_updates_found_body, realUpdateCount,
                realUpdateCount);

        // Get the notification ready
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_system_update).setWhen(System.currentTimeMillis())
                .setTicker(res.getString(R.string.not_new_updates_found_ticker))
                .setContentTitle(res.getString(R.string.not_new_updates_found_title)).setContentText(text)
                .setContentIntent(contentIntent).setLocalOnly(true).setAutoCancel(true);

        LinkedList<UpdateInfo> realUpdates = new LinkedList<UpdateInfo>();
        for (UpdateInfo ui : availableUpdates) {
            if (ui.isNewerThanInstalled()) {
                realUpdates.add(ui);
            }
        }

        Collections.sort(realUpdates, new Comparator<UpdateInfo>() {
            @Override
            public int compare(UpdateInfo lhs, UpdateInfo rhs) {
                /* sort by date descending */
                long lhsDate = lhs.getDate();
                long rhsDate = rhs.getDate();
                if (lhsDate == rhsDate) {
                    return 0;
                }
                return lhsDate < rhsDate ? 1 : -1;
            }
        });

        NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(builder)
                .setBigContentTitle(text);
        int added = 0, count = realUpdates.size();

        for (UpdateInfo ui : realUpdates) {
            if (added < EXPANDED_NOTIF_UPDATE_COUNT) {
                inbox.addLine(ui.getName());
                added++;
            }
        }
        if (added != count) {
            inbox.setSummaryText(
                    res.getQuantityString(R.plurals.not_additional_count, count - added, count - added));
        }
        builder.setStyle(inbox);
        builder.setNumber(availableUpdates.size());

        if (count == 1) {
            i = new Intent(this, DownloadReceiver.class);
            i.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
            i.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) realUpdates.getFirst());
            PendingIntent downloadIntent = PendingIntent.getBroadcast(this, 0, i,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            builder.addAction(R.drawable.ic_tab_download, res.getString(R.string.not_action_download),
                    downloadIntent);
        }

        // Trigger the notification
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(R.string.not_new_updates_found_title, builder.build());
    }

    sendBroadcast(finishedIntent);
}

From source file:com.atlas.mars.weatherradar.MainActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (forecast == null) {
        //frLayoutCurrent = (FrameLayout) findViewById(R.id.frLayoutCurrent);
        forecast = new Forecast(this, forecastLinearLayout);
    } else if (updateForecastIsNeeded()) {
        if (forecast != null) {
            forecast.onRegen();//from  w  ww.java2 s . c  o  m
        } else {
            // frLayoutCurrent = (FrameLayout) findViewById(R.id.frLayoutCurrent);
            forecast = new Forecast(this, forecastLinearLayout);
        }
    }

    //  startService(new Intent(this, MyService.class));
    onCreateMyReceiver();
    //setMyTitle(pager.getCurrentItem());
    Bundle extras = getIntent().getExtras();

    if (pager.getCurrentItem() == 0) {
        alarmRegenBorispol = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        borispolRegenIntent = createIntent("borispolAction", "regetExtras", RegenBorispolBroadCast.class);
        pIntent3 = PendingIntent.getBroadcast(this, 0, borispolRegenIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmRegenBorispol.cancel(pIntent3);
        alarmRegenBorispol.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2 * 60 * 1000,
                2 * 60 * 1000, pIntent3);
    }

    Log.d(TAG, "Current page: " + pager.getCurrentItem());

    fragmentWeather = new CurrentWeather();
    fragmentImageAction = new FragmentImageAction();
    fragmentManager = getFragmentManager();

    if (!isActivityLeave) {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frLayoutCurrent, fragmentWeather);
        fragmentTransaction.commit();
    }
    ;
}

From source file:com.keylesspalace.tusky.MyFirebaseMessagingService.java

private void buildNotification(Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final SharedPreferences notificationPreferences = getApplicationContext()
            .getSharedPreferences("Notifications", MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;//from   w ww  .j  av a2 s . c  om
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.displayName)) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.displayName);
    }

    SharedPreferences.Editor editor = notificationPreferences.edit();
    editor.putString("current", currentNotifications.toString());
    editor.commit();

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(this, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(this, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(body)).setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (getSystemService(NOTIFICATION_SERVICE))).notify(NOTIFY_ID,
                        builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };

        Picasso.with(this).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);

        try {
            builder.setContentTitle(String.format(getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (getSystemService(NOTIFICATION_SERVICE))).notify(NOTIFY_ID, builder.build());
}