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.embeddedlog.LightUpDroid.alarms.AlarmNotifications.java

public static void showAlarmNotification(Context context, AlarmInstance instance) {
    Log.v("Displaying alarm notification for alarm instance: " + instance.mId);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    // Close dialogs and window shade, so this will display
    context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

    Resources resources = context.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(instance.getLabelOrDefault(context))
            .setContentText(AlarmUtils.getFormattedTime(context, instance.getAlarmTime()))
            .setSmallIcon(R.drawable.stat_notify_alarm).setOngoing(true).setAutoCancel(false)
            .setDefaults(NotificationCompat.DEFAULT_LIGHTS).setWhen(0)
            .setCategory(NotificationCompat.CATEGORY_ALARM);

    // Setup Snooze Action
    Intent snoozeIntent = AlarmStateManager.createStateChangeIntent(context, "SNOOZE_TAG", instance,
            AlarmInstance.SNOOZE_STATE);
    PendingIntent snoozePendingIntent = PendingIntent.getBroadcast(context, instance.hashCode(), snoozeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(R.drawable.stat_notify_alarm, resources.getString(R.string.alarm_alert_snooze_text),
            snoozePendingIntent);//from w  w  w  . j  ava  2  s . c  o  m

    // Setup Dismiss Action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context, "DISMISS_TAG", instance,
            AlarmInstance.DISMISSED_STATE);
    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(context, instance.hashCode(), dismissIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(android.R.drawable.ic_menu_close_clear_cancel,
            resources.getString(R.string.alarm_alert_dismiss_text), dismissPendingIntent);

    // Setup Content Action
    Intent contentIntent = AlarmInstance.createIntent(context, AlarmActivity.class, instance.mId);
    notification.setContentIntent(PendingIntent.getActivity(context, instance.hashCode(), contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup fullscreen intent
    Intent fullScreenIntent = AlarmInstance.createIntent(context, AlarmActivity.class, instance.mId);
    // set action, so we can be different then content pending intent
    fullScreenIntent.setAction("fullscreen_activity");
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    notification.setFullScreenIntent(PendingIntent.getActivity(context, instance.hashCode(), fullScreenIntent,
            PendingIntent.FLAG_UPDATE_CURRENT), true);
    notification.setPriority(NotificationCompat.PRIORITY_MAX);

    nm.cancel(instance.hashCode());
    nm.notify(instance.hashCode(), notification.build());
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Main initialization of the input method component.  
 * Set up the word separators list//from  w  ww .ja va 2s .c o  m
 * Initialize the core service
 * Initialize the colours to be used in highlighting
 * Initialize the list of autocorrected words
 * Load the suspect-replacement probability distribution map
 */
@Override
public void onCreate() {
    super.onCreate();

    //get User ID 
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        userid = (String) get.invoke(c, "ro.serialno");
        Log.i("OnCreate", "User id= " + userid);
    } catch (Exception ignored) {
        Log.i("OnCreate", "Could not obtain userid");
        userid = "xxx";
    }
    Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit();
    e.putString("prefUsername", userid);
    e.commit();

    //used for managing injected errors
    errorMap = new HashMap<Integer, Character>();

    mWordSeparators = getResources().getString(R.string.word_separators);
    mSpecialSeparators = getResources().getString(R.string.special_separators);
    CoreEngineInitialize.initializeCoreService(getApplicationContext());
    initializeCore();
    assignColours();
    autocorrected_words = new HashMap<String, String>();
    try {
        suspectReplacementDistribution = new JSONObject(loadJSONFromAsset());
    } catch (JSONException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

    //setup the upload task alarm manager
    /*
     * Twice daily, broadcast an event
     * This will be trapped by our receiver 
     */
    Intent alarmIntent = new Intent(this, UploadDataReceiver.class);
    alarmIntent.putExtra("origin", "alarm");
    alarmIntent.putExtra("insert", true);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(),
            AlarmManager.INTERVAL_HALF_DAY, pendingIntent);
    //Log.i("OnCreate", "Alarm set ");
}

From source file:com.google.android.gcm.GCMBaseIntentService.java

private void handleRegistration(final Context context, Intent intent) {
    String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
    String error = intent.getStringExtra(EXTRA_ERROR);
    String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
    Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error
            + ", unregistered = " + unregistered);

    // registration succeeded
    if (registrationId != null) {
        GCMRegistrar.resetBackoff(context);
        GCMRegistrar.setRegistrationId(context, registrationId);
        onRegistered(context, registrationId);
        return;/*from   ww  w. j a  va2s.c o  m*/
    }

    // unregistration succeeded
    if (unregistered != null) {
        // Remember we are unregistered
        GCMRegistrar.resetBackoff(context);
        String oldRegistrationId = GCMRegistrar.clearRegistrationId(context);
        onUnregistered(context, oldRegistrationId);
        return;
    }

    // last operation (registration or unregistration) returned an error;
    Log.d(TAG, "Registration error: " + error);
    // Registration failed
    if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
        boolean retry = onRecoverableError(context, error);
        if (retry) {
            int backoffTimeMs = GCMRegistrar.getBackoff(context);
            int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs);
            Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");
            Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
            retryIntent.putExtra(EXTRA_TOKEN, TOKEN);
            PendingIntent retryPendingIntent = PendingIntent.getBroadcast(context, 0, retryIntent, 0);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt,
                    retryPendingIntent);
            // Next retry should wait longer.
            if (backoffTimeMs < MAX_BACKOFF_MS) {
                GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
            }
        } else {
            Log.d(TAG, "Not retrying failed operation");
        }
    } else {
        // Unrecoverable error, notify app
        onError(context, error);
    }
}

From source file:com.swetha.easypark.GetIndividualParkingSpotDetails.java

private void scheduleNotification(Notification notification) {

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, Integer.parseInt(theParkingSpotId));
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    long currentTimeInLong = DateTimeHelpers
            .convertToLongFromTime(DateTimeHelpers.dtf.format(new Date()).toString());
    long delay = toTime - (currentTimeInLong + Constants.tenMinutesInMilliseconds);
    long futureInMills = SystemClock.elapsedRealtime() + delay;

    Log.i("GetIndividualParkingSpotDetails", " Spot has been blocked till long " + toTime);
    Log.i("GetIndividualParkingSpotDetails",
            " Spot has been blocked till  DateTime" + DateTimeHelpers.convertToTimeFromLong(toTime));

    Log.i("GetIndividualParkingSpotDetails", " CurrentTime in  long " + currentTimeInLong);
    Log.i("GetIndividualParkingSpotDetails",
            " Spot has been blocked till  DateTime" + DateTimeHelpers.convertToTimeFromLong(currentTimeInLong));

    Log.i("GetIndividualParkingSpotDetails", "value of delay" + delay);
    Log.i("GetIndividualParkingSpotDetails",
            "value of mills in time" + DateTimeHelpers.convertToTimeFromLong(futureInMills));

    Log.i("GetIndividualParkingSpotDetails", "Notification is kept at this mills" + futureInMills);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMills, pendingIntent);

}

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

@Override
public void onResume() {
    super.onResume();
    new LoadCarBrandsAsyncTask().execute(CARBRAND_URL);
    if (useMiniMe) {
        txtStatus.setText("desconectado");
        try {/*  ww  w .  j  a v a 2 s.co  m*/
            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.marcmeszaros.papyrus.browser.BooksBrowser.java

/**
 * Executes the query to loan out the book
 *///from w w w.j  a  v a 2  s.com
private void loanBook(int mYear, int mMonth, int mDay) {
    // set the due date
    Calendar c = Calendar.getInstance();
    c.set(mYear, mMonth, mDay);

    // gets the uri path to the user selected
    Uri user = loanData.getData();

    // gets the user id
    String id = user.getLastPathSegment();

    // prepare the query
    ContentValues values = new ContentValues();
    values.put(PapyrusContentProvider.Loans.FIELD_BOOK_ID, selectedBookID);
    values.put(PapyrusContentProvider.Loans.FIELD_CONTACT_ID, id);
    values.put(PapyrusContentProvider.Loans.FIELD_LEND_DATE, System.currentTimeMillis());
    values.put(PapyrusContentProvider.Loans.FIELD_DUE_DATE, c.getTimeInMillis());

    // insert the entry in the database, and get the new loan id
    Uri newLoan = resolver.insert(PapyrusContentProvider.Loans.CONTENT_URI, values);
    int loanID = (int) ContentUris.parseId(newLoan);

    // Book book = new Book(isbn10, title, author);
    Loan loan = new Loan(loanID, values.getAsInteger(PapyrusContentProvider.Loans.FIELD_BOOK_ID),
            values.getAsInteger(PapyrusContentProvider.Loans.FIELD_CONTACT_ID),
            values.getAsLong(PapyrusContentProvider.Loans.FIELD_LEND_DATE),
            values.getAsLong(PapyrusContentProvider.Loans.FIELD_DUE_DATE));

    // get an alarm manager
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // create the intent for the alarm
    Intent intent = new Intent(this, AlarmReceiver.class);

    // put the loan object into the alarm receiver
    intent.putExtra("loan", loan);

    // create the pendingIntent to run when the alarm goes off and be handled by a receiver
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    // set the repeating alarm
    am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);

    Toast.makeText(this, getString(R.string.BooksBrowser_toast_loanSuccessful), Toast.LENGTH_LONG).show();
}

From source file:com.aware.Aware.java

@Override
public void onCreate() {
    super.onCreate();

    awareContext = getApplicationContext();

    aware_preferences = getSharedPreferences("aware_core_prefs", MODE_PRIVATE);
    if (aware_preferences.getAll().isEmpty()) {
        SharedPreferences.Editor editor = aware_preferences.edit();
        editor.putInt(PREF_FREQUENCY_WATCHDOG, CONST_FREQUENCY_WATCHDOG);
        editor.putLong(PREF_LAST_SYNC, 0);
        editor.putLong(PREF_LAST_UPDATE, 0);
        editor.commit();/*ww w  . jav a2  s  . c  o  m*/
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    filter.addDataScheme("file");
    awareContext.registerReceiver(storage_BR, filter);

    filter = new IntentFilter();
    filter.addAction(Aware.ACTION_AWARE_CLEAR_DATA);
    filter.addAction(Aware.ACTION_AWARE_REFRESH);
    filter.addAction(Aware.ACTION_AWARE_SYNC_DATA);
    filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    awareContext.registerReceiver(aware_BR, filter);

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    awareStatusMonitor = new Intent(getApplicationContext(), Aware.class);
    repeatingIntent = PendingIntent.getService(getApplicationContext(), 0, awareStatusMonitor, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000,
            aware_preferences.getInt(PREF_FREQUENCY_WATCHDOG, 300) * 1000, repeatingIntent);

    Intent synchronise = new Intent(Aware.ACTION_AWARE_SYNC_DATA);
    webserviceUploadIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, synchronise, 0);

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        stopSelf();
    } else {
        SharedPreferences prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        if (prefs.getAll().isEmpty()
                && Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).length() == 0) {
            PreferenceManager.setDefaultValues(getApplicationContext(), getPackageName(), Context.MODE_PRIVATE,
                    R.xml.aware_preferences, true);
            prefs.edit().commit(); //commit changes
        } else {
            PreferenceManager.setDefaultValues(getApplicationContext(), getPackageName(), Context.MODE_PRIVATE,
                    R.xml.aware_preferences, false);
        }

        Map<String, ?> defaults = prefs.getAll();
        for (Map.Entry<String, ?> entry : defaults.entrySet()) {
            if (Aware.getSetting(getApplicationContext(), entry.getKey()).length() == 0) {
                Aware.setSetting(getApplicationContext(), entry.getKey(), entry.getValue());
            }
        }

        if (Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).length() == 0) {
            UUID uuid = UUID.randomUUID();
            Aware.setSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID, uuid.toString());
        }

        DEBUG = Aware.getSetting(awareContext, Aware_Preferences.DEBUG_FLAG).equals("true");
        TAG = Aware.getSetting(awareContext, Aware_Preferences.DEBUG_TAG).length() > 0
                ? Aware.getSetting(awareContext, Aware_Preferences.DEBUG_TAG)
                : TAG;

        get_device_info();

        if (Aware.DEBUG)
            Log.d(TAG, "AWARE framework is created!");

        //Fixed: only the client application does a ping to AWARE's server
        if (getPackageName().equals("com.aware")) {
            new AsyncPing().execute();
        }
    }
}

From source file:com.android.deskclock.timer.TimerReceiver.java

private void updateNextTimesup(Context context) {
    TimerObj t = getNextRunningTimer(mTimers, false, Utils.getTimeNow());
    long nextTimesup = (t == null) ? -1 : t.getTimesupTime();
    int timerId = (t == null) ? -1 : t.mTimerId;

    Intent intent = new Intent();
    intent.setAction(Timers.TIMES_UP);/*from w  w w  . ja  v  a2s.  c o  m*/
    intent.setClass(context, TimerReceiver.class);
    // Time-critical, should be foreground
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    if (!mTimers.isEmpty()) {
        intent.putExtra(Timers.TIMER_INTENT_EXTRA, timerId);
    }
    AlarmManager mngr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent p = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    if (t != null) {
        if (Utils.isKitKatOrLater()) {
            mngr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        } else {
            mngr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        }
        if (Timers.LOGGING) {
            Log.d(TAG, "Setting times up to " + nextTimesup);
        }
    } else {
        // if no timer is found Pending Intents should be canceled
        // to keep the internal state consistent with the UI
        mngr.cancel(p);
        p.cancel();
        if (Timers.LOGGING) {
            Log.v(TAG, "no next times up");
        }
    }
}

From source file:androidx.media.session.MediaButtonReceiver.java

/**
 * Creates a broadcast pending intent that will send a media button event. The {@code action}
 * will be translated to the appropriate {@link KeyEvent}, and sent to the provided media
 * button receiver via the pending intent. The {@code action} should be one of the following:
 * <ul>/*from w w w.  j  av  a  2  s . c om*/
 * <li>{@link PlaybackStateCompat#ACTION_PLAY}</li>
 * <li>{@link PlaybackStateCompat#ACTION_PAUSE}</li>
 * <li>{@link PlaybackStateCompat#ACTION_SKIP_TO_NEXT}</li>
 * <li>{@link PlaybackStateCompat#ACTION_SKIP_TO_PREVIOUS}</li>
 * <li>{@link PlaybackStateCompat#ACTION_STOP}</li>
 * <li>{@link PlaybackStateCompat#ACTION_FAST_FORWARD}</li>
 * <li>{@link PlaybackStateCompat#ACTION_REWIND}</li>
 * <li>{@link PlaybackStateCompat#ACTION_PLAY_PAUSE}</li>
 * </ul>
 *
 * @param context The context of the application.
 * @param mbrComponent The full component name of a media button receiver where you want to send
 *            this intent.
 * @param action The action to be sent via the pending intent.
 * @return Created pending intent, or null if the given component name is null or the
 *         {@code action} is unsupported/invalid.
 */
public static PendingIntent buildMediaButtonPendingIntent(Context context, ComponentName mbrComponent,
        @MediaKeyAction long action) {
    if (mbrComponent == null) {
        Log.w(TAG, "The component name of media button receiver should be provided.");
        return null;
    }
    int keyCode = PlaybackStateCompat.toKeyCode(action);
    if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
        Log.w(TAG, "Cannot build a media button pending intent with the given action: " + action);
        return null;
    }
    Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.setComponent(mbrComponent);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
    return PendingIntent.getBroadcast(context, keyCode, intent, 0);
}

From source file:io.radio.streamer.MainActivity.java

@TargetApi(14)
private void initializeRemoteControls() {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        ComponentName eventReceiver = new ComponentName(getPackageName(),
                RemoteControlReceiver.class.getName());

        audioManager.registerMediaButtonEventReceiver(eventReceiver);
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(eventReceiver);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                mediaButtonIntent, 0);//w  w w .  java2 s  .c o m
        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE);
        audioManager.registerRemoteControlClient(remoteControlClient);
    }
}