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:de.appplant.cordova.plugin.notification.NotificationWrapper.java

/** 
 * Update an existing notification //from   w ww .ja v  a2s  . co m
 * 
 * @param updates JSONObject with update-content
 */
public void update(JSONObject updates) {
    String id = updates.optString("id", "0");

    // update shared preferences
    SharedPreferences settings = getSharedPreferences();
    Map<String, ?> alarms = settings.getAll();
    JSONObject arguments;
    try {
        arguments = new JSONObject(alarms.get(id).toString());
    } catch (JSONException e) {
        Log.e("NotificationWrapper", "Update failed. No Notification available for the given id: " + id);
        return;
    }
    arguments = updateArguments(arguments, updates);

    // cancel existing alarm
    Intent intent = new Intent(context, receiver).setAction("" + id);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager am = getAlarmManager();
    am.cancel(pi);

    //add new alarm
    Options options = new Options(context).parse(arguments);
    schedule(options);
}

From source file:com.jameswolfeoliver.pigeon.Services.MessageReplyService.java

private void sendTextMessage(final Conversation conversation, String message) {
    ArrayList<String> messageParts = SmsManager.getDefault().divideMessage(message);

    SmsBroadcastReceiver sentSmsBroadcastReceiver = new SmsBroadcastReceiver(messageParts.size()) {
        MessageInfo messageInfo = new MessageInfo();

        @Override/*from ww w.j  a  v  a 2s .  c  o m*/
        public void onReceive(Context context, Intent intent) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                messageInfo.fail("Error - Generic failure");
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                messageInfo.fail("Error - No Service");
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                messageInfo.fail("Error - Null PDU");
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                messageInfo.fail("Error - Radio off");
                break;
            }

            numberOfMessageParts--;
            if (numberOfMessageParts <= 0) {
                unregisterReceiver(this);
                if (messageInfo.isFailed()) {
                    Log.d(LOG_TAG, "Send SMS Failure");
                } else {
                    Log.d(LOG_TAG, "Send SMS Success");
                }
            }
        }
    };

    SmsBroadcastReceiver deliveredSmsBroadcastReceiver = new SmsBroadcastReceiver(messageParts.size()) {
        @Override
        public void onReceive(Context context, Intent intent) {
            numberOfMessageParts--;
            if (numberOfMessageParts <= 0) {
                unregisterReceiver(this);
                NotificationsManager.removeAllNotificationsForConversation(conversation.getThreadId(), context);
                Log.d(LOG_TAG, "SMS Delivered");

            }
        }
    };

    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>(messageParts.size());
    Intent sentIntent = new Intent(SENT_ACTION);

    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>(messageParts.size());
    Intent deliveredIntent = new Intent(DELIVERED_ACTION);

    for (int i = 0; i < messageParts.size(); i++) {
        sentPendingIntents.add(PendingIntent.getBroadcast(this, 0, sentIntent, 0));
        deliveredPendingIntents.add(PendingIntent.getBroadcast(this, 0, deliveredIntent, 0));
    }

    registerReceiver(sentSmsBroadcastReceiver, new IntentFilter(SENT_ACTION));
    registerReceiver(deliveredSmsBroadcastReceiver, new IntentFilter(DELIVERED_ACTION));
    SmsManager.getDefault().sendMultipartTextMessage(Long.toString(conversation.getAddress()), null,
            messageParts, sentPendingIntents, deliveredPendingIntents);
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

private void notificationService() {
    //Create an Intent for the BroadcastReceiver
    Intent buttonIntent = new Intent(this, ButtonReceiver.class);
    buttonIntent.putExtra("notificationId", NOTIF_ID);

    //Create the PendingIntent
    PendingIntent cancelNotification = PendingIntent.getBroadcast(this, 0, buttonIntent, 0);

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle("The Jones Theory").setOngoing(true)
            .setContentText("Preparing to download Science...")
            .addAction(R.drawable.ic_action_close, "Hide", cancelNotification)
            .setSmallIcon(R.drawable.ic_action_file_download)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

    // Sets an activity indicator for an operation of indeterminate length
    mBuilder.setProgress(0, 0, true);//  w w  w.j  av a 2  s .  c  om
    // Issues the notification
    mNotifyManager.notify(NOTIF_ID, mBuilder.build());
}

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

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

    // Cancel Alarm using Reminder ID
    mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AutomuteAlarmReceiver.class),
            0);/*  w ww.ja  v a 2 s.c o m*/
    mAlarmManager.cancel(mPendingIntent);

    // Disable alarm
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:com.grupohqh.carservices.operator.ReadTagActivity.java

@Override
public void onResume() {
    super.onResume();
    etSerialNumber.setText("");
    etLicensePlate.setText("");
    etTag.setText("");
    if (useMiniMe) {
        etEpc.setText("");
        txtStatus.setText("desconectado");
        try {// ww  w  . j a va  2s . c om
            HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
            Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
            while (deviceIterator.hasNext()) {
                UsbDevice device = deviceIterator.next();
                if (device.getProductId() == PID && device.getVendorId() == VID)
                    if (!manager.hasPermission(device)) {
                        txtStatus.setText("sin permisos");
                        manager.requestPermission(device,
                                PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0));
                        break;
                    } else {
                        txtStatus.setText("conectado");
                    }
            }
        } catch (Exception e) {
            Log.d("USB error", e.getMessage());
        }
    }
}

From source file:ca.hoogit.hooold.Scheduling.Sms.java

private ArrayList<PendingIntent> generateIntents(Context context, String action, String recipient,
        int recipientCount, int partCount) {
    ArrayList<PendingIntent> pendingIntents = new ArrayList<>();
    for (int i = 1; i <= partCount; i++) {
        Intent intent = generateIntent(action, recipient, recipientCount);
        intent.putExtra(Consts.KEY_SMS_PARTS, partCount);
        intent.putExtra(Consts.KEY_SMS_PART, i);

        PendingIntent pending = PendingIntent.getBroadcast(context, (int) id, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        pendingIntents.add(pending);/*from  w w w . j  a va2 s.  c  o m*/
    }
    return pendingIntents;
}

From source file:com.firsttry.mumbaiparking.helpers.MyAlarmManager.java

public void setAlarm(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("Reminders", 0);

    Calendar cal = Calendar.getInstance();
    int currentDate = cal.get(cal.DATE);
    int currentMonth = cal.get(cal.MONTH);
    int currentYear = cal.get(cal.YEAR);

    int pucDate = prefs.getInt("PUC_DATE", 0);
    int pucMonth = prefs.getInt("PUC_MONTH", 0);
    int pucYear = prefs.getInt("PUC_YEAR", 0);

    int insuranceDate = prefs.getInt("INSURANCE_DATE", 0);
    int insuranceMonth = prefs.getInt("INSURANCE_MONTH", 0);
    int insuranceYear = prefs.getInt("INSURANCE_YEAR", 0);

    int licenseDate = prefs.getInt("LICENSE_DATE", 0);
    int licenseMonth = prefs.getInt("LICENSE_MONTH", 0);
    int licenseYear = prefs.getInt("LICENSE_YEAR", 0);

    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, MyAlarmManager.class);

    Log.i("Dates", "PUC : " + pucDate + " " + pucMonth + " " + pucYear);
    Log.i("Dates", "Licence : " + licenseDate + " " + licenseMonth + " " + licenseYear);
    Log.i("Dates", "Insurance : " + insuranceDate + " " + insuranceMonth + " " + insuranceYear);
    Log.i("Dates", "current : " + currentDate + " " + currentMonth + " " + currentYear);

    if (pucDate != 0 && (pucMonth - currentMonth) == 0 && (pucYear - currentYear) == 0
            && (pucDate - currentDate) < 7 && (pucDate - currentDate) >= 0) {

        Log.i("setAlarm", "Inside if puc");
        i.putExtra("pucDays", (pucDate - currentDate));
    }/* w  w  w.  j  ava  2  s  .  c  om*/

    if (licenseDate != 0 && (licenseMonth - currentMonth) == 0 && (licenseYear - currentYear) == 0
            && (licenseDate - currentDate) < 7 && (licenseDate - currentDate) >= 0) {
        Log.i("setAlarm", "Inside if license");
        i.putExtra("licenseDays", (licenseDate - currentDate));
    }

    if (insuranceDate != 0 && (insuranceMonth - currentMonth) == 0 && (insuranceYear - currentYear) == 0
            && (insuranceDate - currentDate) < 7 && (insuranceDate - currentDate) >= 0) {
        Log.i("setAlarm", "Inside if insurance");
        //i.putExtra("type", "Insurance");
        i.putExtra("insuranceDays", (insuranceDate - currentDate));
    }

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 10, pi);
}

From source file:gpsalarm.app.service.PostMonitor.java

@Override
public void onCreate() {
    super.onCreate();
    sdb = new TimelineHelper(this);
    rdb = new ReminderHelper(this);

    //get user account from preference.
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    team = prefs.getString("team", "").toUpperCase();
    myAccount = new Account(prefs.getString("user", null), prefs.getString("password", ""), null);

    registerReceiver(onBatteryChanged, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, OnAlarmReceiver.class);
    pi = PendingIntent.getBroadcast(this, 0, i, 0);
    setAlarm(INITIAL_POLL_PERIOD);/* w w  w.  ja  va  2  s . co m*/
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void refreshNotification(Context context, boolean noTimeline) {
    AppSettings settings = AppSettings.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
    int currentAccount = sharedPrefs.getInt("current_account", 1);

    //int[] unreadCounts = new int[] {4, 1, 2}; // for testing
    int[] unreadCounts = getUnreads(context);

    int timeline = unreadCounts[0];
    int realTimelineCount = timeline;

    // if they don't want that type of notification, simply set it to zero
    if (!settings.timelineNot || (settings.pushNotifications && settings.liveStreaming) || noTimeline) {
        unreadCounts[0] = 0;/*from  w w w  .  j  a va 2  s.c  om*/
    }
    if (!settings.mentionsNot) {
        unreadCounts[1] = 0;
    }
    if (!settings.dmsNot) {
        unreadCounts[2] = 0;
    }

    if (unreadCounts[0] == 0 && unreadCounts[1] == 0 && unreadCounts[2] == 0) {

    } else {
        Intent markRead = new Intent(context, MarkReadService.class);
        PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

        String shortText = getShortText(unreadCounts, context, currentAccount);
        String longText = getLongText(unreadCounts, context, currentAccount);
        // [0] is the full title and [1] is the screenname
        String[] title = getTitle(unreadCounts, context, currentAccount);
        boolean useExpanded = useExp(context);
        boolean addButton = addBtn(unreadCounts);

        if (title == null) {
            return;
        }

        Intent resultIntent;

        if (unreadCounts[1] != 0 && unreadCounts[0] == 0) {
            // it is a mention notification (could also have a direct message)
            resultIntent = new Intent(context, RedirectToMentions.class);
        } else {
            resultIntent = new Intent(context, MaterialMainActivity.class);
        }

        PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

        NotificationCompat.Builder mBuilder;

        Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

        mBuilder = new NotificationCompat.Builder(context).setContentTitle(title[0])
                .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings))
                .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(getIcon(context, unreadCounts, title[1]))
                .setContentIntent(resultPendingIntent).setAutoCancel(true)
                .setTicker(TweetLinkUtils.removeColorHtml(shortText, settings))
                .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        if (unreadCounts[1] > 1 && unreadCounts[0] == 0 && unreadCounts[2] == 0) {
            // inbox style notification for mentions
            mBuilder.setStyle(getMentionsInboxStyle(unreadCounts[1], currentAccount, context,
                    TweetLinkUtils.removeColorHtml(shortText, settings)));
        } else if (unreadCounts[2] > 1 && unreadCounts[0] == 0 && unreadCounts[1] == 0) {
            // inbox style notification for direct messages
            mBuilder.setStyle(getDMInboxStyle(unreadCounts[1], currentAccount, context,
                    TweetLinkUtils.removeColorHtml(shortText, settings)));
        } else {
            // big text style for an unread count on timeline, mentions, and direct messages
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                    settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title[0], shortText);
        }

        // Light Flow notification
        sendToLightFlow(context, title[0], shortText);

        int homeTweets = unreadCounts[0];
        int mentionsTweets = unreadCounts[1];
        int dmTweets = unreadCounts[2];

        int newC = 0;

        if (homeTweets > 0) {
            newC++;
        }
        if (mentionsTweets > 0) {
            newC++;
        }
        if (dmTweets > 0) {
            newC++;
        }

        if (settings.notifications && newC > 0) {

            if (settings.vibrate) {
                mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
            }

            if (settings.sound) {
                try {
                    mBuilder.setSound(Uri.parse(settings.ringtone));
                } catch (Exception e) {
                    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                }
            }

            if (settings.led)
                mBuilder.setLights(0xFFFFFF, 1000, 1000);

            // Get an instance of the NotificationManager service
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

            if (addButton) { // the reply and read button should be shown

                Log.v("username_for_noti", title[1]);
                sharedPrefs.edit().putString("from_notification", "@" + title[1] + " " + title[2]).commit();
                MentionsDataSource data = MentionsDataSource.getInstance(context);
                long id = data.getLastIds(currentAccount)[0];
                PendingIntent replyPending = PendingIntent.getActivity(context, 0, null, 0);
                sharedPrefs.edit().putLong("from_notification_long", id).commit();
                sharedPrefs.edit()
                        .putString("from_notification_text",
                                "@" + title[1] + ": " + TweetLinkUtils.removeColorHtml(shortText, settings))
                        .commit();

                // Create the remote input
                RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                        .setLabel("@" + title[1] + " ").build();

                // Create the notification action
                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
                        R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply),
                        replyPending).addRemoteInput(remoteInput).build();

                NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
                        R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read),
                        readPending);

                mBuilder.addAction(replyAction);
                mBuilder.addAction(action.build());
            }

            // Build the notification and issues it with notification manager.
            notificationManager.notify(1, mBuilder.build());

            // if we want to wake the screen on a new message
            if (settings.wakeScreen) {
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                        | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
                wakeLock.acquire(5000);
            }
        }

        // if there are unread tweets on the timeline, check them for favorite users
        if (settings.favoriteUserNotifications && realTimelineCount > 0) {
            favUsersNotification(currentAccount, context);
        }
    }

    try {

        ContentValues cv = new ContentValues();

        cv.put("tag", "com.daiv.android.twitter/com.daiv.android.twitter.ui.MainActivity");

        // add the direct messages and mentions
        cv.put("count", unreadCounts[1] + unreadCounts[2]);

        context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);

    } catch (IllegalArgumentException ex) {

        /* Fine, TeslaUnread is not installed. */

    } catch (Exception ex) {

        /* Some other error, possibly because the format
           of the ContentValues are incorrect.
                
        Log but do not crash over this. */

        ex.printStackTrace();

    }
}

From source file:co.vanir.indecentxposure.IndecentXposure.java

public static void notify(final Context context, final String exampleString) {
    final Resources res = context.getResources();

    final String ticker = exampleString;
    final String title = res.getString(R.string.solve_problems_notification_title); //_template, exampleString);
    final String text = res.getString(R.string.solve_problems_notification_placeholder_text_template);//, exampleString);

    //one button opens the "uninstall app" settings page
    final Intent removeIntent = new Intent();
    removeIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", SerialOffender.getPackageName(), null);
    removeIntent.setData(uri);//from ww  w .  j ava2 s  . c o m

    //the other option will hide the notification until the user uninstalls and reinstalls
    //  the installer
    final Intent ignoreIntent = new Intent();
    ignoreIntent.setAction("co.vanir.indecentxposure.IGNORE_LIKELY_FUNK");

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_stat_solve_problems).setContentTitle(title).setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_MAX).setTicker(ticker)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(text).setBigContentTitle(title)
                    .setSummaryText(res.getString(R.string.summary_thanks)))
            .addAction(0, res.getString(R.string.action_remove),
                    PendingIntent.getActivity(context, 0, removeIntent, PendingIntent.FLAG_UPDATE_CURRENT))
            .addAction(0, res.getString(R.string.action_accept_consequences),
                    PendingIntent.getBroadcast(context, 0, ignoreIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    notify(context, builder.build(), true);
}