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.omt.syncpad.DemoKitActivity.java

/** Called when the activity is first created. */
@Override/* w w  w. j  a  va2 s. c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mUsbManager = UsbManager.getInstance(this);
    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) {
        mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
        openAccessory(mAccessory);
    }

    setContentView(R.layout.main);

    enableControls(false);
}

From source file:at.andreasrohner.spartantimelapserec.BackgroundService.java

@SuppressWarnings("deprecation")
@Override// w w w.  ja v  a2s.c o  m
public void onCreate() {
    created = true;

    settings = new RecSettings();
    settings.load(getApplicationContext(),
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));

    createNotification(NOTIFICATION_ID);

    if (settings.isSchedRecEnabled() && settings.getSchedRecTime() > System.currentTimeMillis() + 10000) {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(), ScheduleReceiver.class);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

        alarmMgr.set(AlarmManager.RTC_WAKEUP, settings.getSchedRecTime(), alarmIntent);

        stopSelf();
        return;
    }

    // Create new SurfaceView, set its size to 1x1, move
    // it to the top left corner and set this service as a callback
    WindowManager winMgr = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    surfaceView = new SurfaceView(this);
    // deprecated setting, but required on Android versions prior to 3.0
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    surfaceView.getHolder().addCallback(this);

    LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT);
    layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
    winMgr.addView(surfaceView, layoutParams);

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.setReferenceCounted(false);
    wakeLock.acquire();
}

From source file:com.googlecode.android_scripting.facade.USBHostSerialFacade.java

/**
 * collectUSBDevices: start USB connection, from usbserialConnect {{{1
 *///from w w w.  j a v a2s.  c  o m
private String connectUSBDevice(String hash) {
    Integer nHash;
    String ret = "";
    boolean deviceFound = false;

    PendingIntent mPermissionIntent = PendingIntent.getBroadcast(mService, 0, new Intent(ACTION_USB_PERMISSION),
            0);
    Map<String, UsbDevice> map = mUsbManager.getDeviceList();

    if (hash.equals("")) {
        nHash = 0;
    } else {
        nHash = Integer.parseInt(hash);
    }

    Log.d("USBHostSerial: collectUSBDevices()");
    for (UsbDevice device : map.values()) {
        Log.d("USBHostSerial: try to check " + device.hashCode());
        if (!(nHash == 0) && (nHash != device.hashCode())) {
            continue;
        }
        Log.d("USBHostSerial: requestPermission to =>" + device.getDeviceName());

        UsbSerialConnection conn;
        try {
            conn = new UsbSerialConnection();
        } catch (IOException e) {
            Log.d("can't create UsbSerialConnection object");
            continue;
        }
        conn.mDevice = device;
        conn.options = new String(options);
        addConnection(conn);

        mUsbManager.requestPermission(device, mPermissionIntent);
        deviceFound = true;
        ret += ",\"" + conn.getUUID() + "\"";
    }
    if (!deviceFound) {
        connectionFailed();
        return "device not found";
    }
    return "[\"OK\"" + ret + "]";
}

From source file:com.commontime.plugin.notification.notification.Builder.java

/**
 * Set intent to handle the delete event. Will clean up some persisted
 * preferences.//  www.  j  a  va 2s.c  om
 *
 * @param builder
 *      Local notification builder instance
 */
private void applyDeleteReceiver(NotificationCompat.Builder builder) {

    if (clearReceiver == null)
        return;

    Intent deleteIntent = new Intent(context, clearReceiver).setAction(options.getIdStr())
            .putExtra(Options.EXTRA, options.toString());

    PendingIntent dpi = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    builder.setDeleteIntent(dpi);
}

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

public void stop() {
    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctx, Receiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    am.cancel(pi);//from   w w  w. java  2s . c  om
}

From source file:com.footprint.cordova.plugin.localnotification.LocalNotification.java

/**
 * Cancel a specific notification that was previously registered.
 *
 * @param notificationId//from  ww  w.  ja v  a 2s .  com
 *            The original ID of the notification that was used when it was
 *            registered using add()
 */
public static void cancel(String notificationId) {
    /*
     * Create an intent that looks similar, to the one that was registered
     * using add. Making sure the notification id in the action is the same.
     * Now we can search for such an intent using the 'getService' method
     * and cancel it.
     */
    Intent intent = new Intent(context, Receiver.class).setAction("" + notificationId);

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager am = getAlarmManager();
    NotificationManager nc = getNotificationManager();

    am.cancel(pi);

    try {
        nc.cancel(Integer.parseInt(notificationId));
    } catch (Exception e) {
    }

    fireEvent("cancel", notificationId, "");
}

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

public void setRepeatAlarm(Context context, Calendar calendar, int ID, long RepeatTime) {
    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 timein
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using initial notification time and repeat interval time
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime,
            RepeatTime, 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:cn.studyjams.s2.sj0119.NForget.AlarmReceiver.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, AlarmReceiver.class), 0);
    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.jmstudios.redmoon.receiver.AutomaticFilterChangeReceiver.java

public static void scheduleNextAlarm(Context context, String time, Intent operation) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
    calendar.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

    GregorianCalendar now = new GregorianCalendar();
    now.add(Calendar.SECOND, 1);/* w  w  w.ja v  a  2  s  .  c o  m*/
    if (calendar.before(now)) {
        calendar.add(Calendar.DATE, 1);
    }

    if (DEBUG)
        Log.i(TAG, "Scheduling alarm for " + calendar.toString());

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, operation, 0);

    if (android.os.Build.VERSION.SDK_INT >= 19) {
        alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
    }
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override//from  w ww  .ja  v  a  2  s .co m
protected void onHandleIntent(Intent intent) {
    Timber.d("Waking up...");
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
        return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
        Timber.d("Notification service disabled, removing wakup-up alarm");
        // cancel any pending alarm
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, OnAlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.cancel(pi);

        resetLastEpisodeAirtime(prefs);

        return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL"));
    if (isFavsOnly) {
        selection.append(" AND ").append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials");
    if (isNoSpecials) {
        selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
    }
    // always exclude hidden shows
    selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);

    final long customCurrentTime = TimeTools.getCurrentTime(this);
    final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION,
            selection.toString(),
            new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING);

    if (upcomingEpisodes != null) {
        int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
        if (DEBUG) {
            Timber.d("DEBUG MODE: notification threshold is 1 week");
            // a week, for debugging (use only one show to get single
            // episode notifications)
            notificationThreshold = 10080;
            // notify again for same episodes
            resetLastEpisodeAirtime(prefs);
        }

        final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
        // wake user-defined amount of time earlier than next episode release time
        final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime()
                - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

        /*
         * Set to -1 as on first run nextTimePlanned will be 0. This assures
         * we still see notifications of upcoming episodes then.
         */
        int newEpisodesAvailable = -1;

        // Check if we did wake up earlier than planned
        if (System.currentTimeMillis() < plannedWakeUpTime) {
            Timber.d("Woke up earlier than planned, checking for new episodes");
            newEpisodesAvailable = 0;
            long latestTimeNotified = NotificationSettings.getLastNotified(this);

            // Check if there are any earlier episodes to notify about
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime < nextEpisodeReleaseTime) {
                    if (releaseTime > latestTimeNotified) {
                        /**
                         * This will not get new episodes which would have
                         * aired the same time as the last one we notified
                         * about. Sad, but the best we can do right now.
                         */
                        newEpisodesAvailable = 1;
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (newEpisodesAvailable == 0) {
            // Go to sleep, wake up as planned
            Timber.d("No new episodes, going to sleep.");
            wakeUpTime = plannedWakeUpTime;
        } else {
            // Get episodes which are within the notification threshold
            // (user set) and not yet cleared
            final List<Integer> notifyPositions = new ArrayList<>();
            final long latestTimeCleared = NotificationSettings.getLastCleared(this);
            final long latestTimeToInclude = customCurrentTime
                    + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            int position = -1;
            upcomingEpisodes.moveToPosition(position);
            while (upcomingEpisodes.moveToNext()) {
                position++;

                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime <= latestTimeToInclude) {
                    /*
                     * Only add those after the last one the user cleared.
                     * At most those of the last 24 hours (see query above).
                     */
                    if (releaseTime > latestTimeCleared) {
                        notifyPositions.add(position);
                    }
                } else {
                    // Too far into the future, stop!
                    break;
                }
            }

            // Notify if we found any episodes
            if (notifyPositions.size() > 0) {
                // store latest air time of all episodes we notified about
                upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
                long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (!AndroidUtils.isHoneycombOrHigher()) {
                    /*
                     * Everything below HC does not have delete intents, so
                     * we just never notify about the same episode twice.
                     */
                    Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime);
                    prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
                }
                Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: "
                        + latestAirtime);
                prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

                onNotify(upcomingEpisodes, notifyPositions, latestAirtime);
            }

            /*
             * Plan next episode to notify about, calc wake-up alarm as
             * early as user wants.
             */
            upcomingEpisodes.moveToPosition(-1);
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime > latestTimeToInclude) {
                    // store next episode we plan to notify about
                    Timber.d("Storing next episode time to notify about: " + releaseTime);
                    prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit();

                    // calc actual wake up time
                    wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime()
                            - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

                    break;
                }
            }
        }

        upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
        wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
        Timber.d("No future episodes found, wake up in 6 hours");
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
}