Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

In this page you can find the example usage for android.app PendingIntent FLAG_UPDATE_CURRENT.

Prototype

int FLAG_UPDATE_CURRENT

To view the source code for android.app PendingIntent FLAG_UPDATE_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Usage

From source file:com.banana.instagrab.helper.NotificationUtils.java

private static PendingIntent contentIntent(Context context) {

    //        String path = "abc"; //folder name
    //        String fileName = "1234.jpg";
    //        String directoryPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM;
    //        File dirFile = new File(directoryPath + File.separator + path);
    //        if (!dirFile.exists()) {
    //            Log.d("JSONTEST", "dirFile.mkdir() result : " + dirFile.mkdir());
    //        }//from  w  w  w . j  a  v  a 2  s  . c  om
    //        File toBeSavedFile = new File(dirFile.getPath() + File.separator + fileName);
    //        Intent intent = new Intent();
    //        intent.setAction(Intent.ACTION_VIEW);
    //        intent.setDataAndType(Uri.parse(toBeSavedFile.toString()), "image/*");

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Awesome message");
    sendIntent.setType("text/plain");

    return PendingIntent.getService(context, WATER_REMINDER_PENDING_INTENT_ID, sendIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //        return PendingIntent.getActivity(
    //                context,
    //                WATER_REMINDER_PENDING_INTENT_ID,
    //                intent,
    //                PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.partner.common.updater.ApkDownloadUtil.java

/**
 * ?/*from   w w  w  .j  a  v  a  2 s. c  o  m*/
 * @param context
 * @param targetClass
 */
private void showAppDownloadNotify(Context context, Class<?> parentClass, Class<?> targetClass) {
    mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    // show notify
    Intent notifyIntent = new Intent(context, targetClass);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack
    if (parentClass != null) {
        stackBuilder.addNextIntent(new Intent(context, parentClass));
    }
    // Adds the Intent to the top of the stack
    stackBuilder.addNextIntent(notifyIntent);
    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setContentTitle(appName).setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(resultPendingIntent);
    mBuilder.setProgress(100, 0, false);
    mNotifyManager.notify(appName.hashCode(), mBuilder.build());
}

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  w w.  j  a  va2 s.  co 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;
}

From source file:com.andrada.sitracker.tasks.receivers.UpdateStatusNotificationReceiver.java

private void sendNotification(int number, List<String> updatedAuthorNames, @NotNull Context context) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    int maxLines = 4;
    if (updatedAuthorNames.size() < maxLines) {
        maxLines = updatedAuthorNames.size();
    }//from  ww  w .  ja va  2 s .  c  o m
    for (int i = 0; i < maxLines; i++) {
        inboxStyle.addLine(updatedAuthorNames.get(i));
    }
    if (updatedAuthorNames.size() > 4) {
        inboxStyle.setSummaryText(
                context.getString(R.string.notification_more_summary, updatedAuthorNames.size() - 4));
    }
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.notification)
            .setContentTitle(context.getResources().getString(R.string.notification_title))
            .setContentText(context.getResources().getQuantityString(R.plurals.authors_updated, number, number))
            .setAutoCancel(true).setOnlyAlertOnce(true)
            .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND).setNumber(number)
            .setStyle(inboxStyle);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, HomeActivity_.class);
    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(HomeActivity_.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(UPDATE_SUCCESS_NOTIFICATION_ID, mBuilder.build());
}

From source file:capstone.se491_phm.gcm.PhmGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.// w w  w  .  j  av a  2s .c  o  m
 */
private void sendNotification(String message) {
    Context context = getBaseContext();
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(Constants.SERVER_IP, message);
    editor.commit();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.notification).setContentTitle("External Sensor Request")
            .setContentText("A connection request has been made from this ip: " + message
                    + ". Click to allow connection")
            .setSound(defaultSoundUri);
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, ExternalSensorActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ExternalSensorActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    // mId allows you to update the notification later on.
    MainActivity.mNotificationManager.notify(notificationId, mBuilder.build());
}

From source file:de.micmun.android.workdaystarget.DaysLeftService.java

/**
 * Updates the days to target.//ww  w.  ja  va2s .co  m
 */
private void updateDays() {
    AppWidgetManager appManager = AppWidgetManager.getInstance(this);
    ComponentName cName = new ComponentName(getApplicationContext(), DaysLeftProvider.class);
    int[] appIds = appManager.getAppWidgetIds(cName);

    DayCalculator dayCalc = new DayCalculator();
    if (!isOnline()) {
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            Log.e(TAG, "Interrupted: " + e.getLocalizedMessage());
        }
    }

    for (int appId : appIds) {
        PrefManager pm = new PrefManager(this, appId);
        Calendar target = pm.getTarget();
        boolean[] chkDays = pm.getCheckedDays();
        int days = pm.getLastDiff();

        if (isOnline()) {
            try {
                days = dayCalc.getDaysLeft(target.getTime(), chkDays);
                Map<String, Object> saveMap = new HashMap<String, Object>();
                Long diff = Long.valueOf(days);
                saveMap.put(PrefManager.KEY_DIFF, diff);
                pm.save(saveMap);
            } catch (JSONException e) {
                Log.e(TAG, "ERROR holidays: " + e.getLocalizedMessage());
            }
        } else {
            Log.e(TAG, "No internet connection!");
        }
        RemoteViews rv = new RemoteViews(this.getPackageName(), R.layout.appwidget_layout);
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        String targetStr = df.format(target.getTime());
        rv.setTextViewText(R.id.target, targetStr);
        String dayStr = String.format(Locale.getDefault(), "%d %s", days,
                getResources().getString(R.string.unit));
        rv.setTextViewText(R.id.dayCount, dayStr);

        // put widget id into intent
        Intent configIntent = new Intent(this, ConfigActivity.class);
        configIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        configIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appId);
        configIntent.setData(Uri.parse(configIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, configIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        rv.setOnClickPendingIntent(R.id.widgetLayout, pendIntent);

        // update widget
        appManager.updateAppWidget(appId, rv);
    }
}

From source file:ca.mudar.mtlaucasou.LocationFragmentActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    mAppHelper = (AppHelper) getApplicationContext();
    mActivityHelper = ActivityHelper.createInstance(this);

    prefs = getSharedPreferences(Const.APP_PREFS_NAME, Context.MODE_PRIVATE);
    prefsEditor = prefs.edit();/*from  ww w.ja  v  a2 s. com*/

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    /**
     * Instantiate a LastLocationFinder class. This will be used to find the
     * last known location when the application starts.
     */
    lastLocationFinder = PlatformSpecificImplementationFactory.getLastLocationFinder(this);
    lastLocationFinder.setChangedLocationListener(oneShotLastLocationUpdateListener);
    hasRegisteredSingleUpdateReceiver = true;

    /**
     * Set the last known location as user's current location.
     */
    mAppHelper.setLocation(lastLocationFinder.getLastBestLocation(Const.MAX_DISTANCE, Const.MAX_TIME));

    /**
     * Specify the Criteria to use when requesting location updates while
     * the application is Active.
     */
    criteria = new Criteria();
    if (Const.USE_GPS_WHEN_ACTIVITY_VISIBLE) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else {
        criteria.setPowerRequirement(Criteria.POWER_LOW);
    }

    /**
     * Setup the location update Pending Intents.
     */
    Intent activeIntent = new Intent(this, LocationChangedReceiver.class);
    locationListenerPendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent passiveIntent = new Intent(this, PassiveLocationChangedReceiver.class);
    locationListenerPassivePendingIntent = PendingIntent.getBroadcast(this, 0, passiveIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    locationManager.removeUpdates(locationListenerPassivePendingIntent);

    /**
     * Instantiate a Location Update Requester class based on the available
     * platform version. This will be used to request location updates.
     */
    locationUpdateRequester = PlatformSpecificImplementationFactory
            .getLocationUpdateRequester(this.getApplicationContext(), locationManager);

    super.onCreate(savedInstanceState);
}

From source file:com.BeatYourRecord.AssignmentSyncService.java

public void sendNotification(String ytdDomain, String assignmentId) {
    int notificationId = 1;

    Intent assignmentIntent = new Intent(this, DetailsActivity.class);
    assignmentIntent.putExtra(DbHelper.YTD_DOMAIN, ytdDomain);
    assignmentIntent.putExtra(DbHelper.ASSIGNMENT_ID, assignmentId);
    assignmentIntent.putExtra("notificationId", notificationId);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, assignmentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Notification n = new Notification(R.drawable.icon, "Update from YouTube Direct",
            System.currentTimeMillis());
    n.setLatestEventInfo(getApplicationContext(), "Update from YouTube Direct",
            "For " + SettingActivity.getYtdDomains(this).get(this.ytdDomain), pendingIntent);
    n.defaults |= Notification.DEFAULT_LIGHTS;
    nm.notify(notificationId, n);/*  w w w.j a  v  a 2  s.c o m*/
}

From source file:com.adam.aslfms.service.ScrobblingService.java

@Override
public void onCreate() {
    settings = new AppSettings(this);
    mDb = new ScrobblesDatabase(this);
    mDb.open();/*from  www.  j  a  v  a 2 s  .co m*/
    mNetManager = new NetworkerManager(this, mDb);

    int sdk = Build.VERSION.SDK_INT;
    if (sdk == Build.VERSION_CODES.GINGERBREAD || sdk == Build.VERSION_CODES.GINGERBREAD_MR1) {
        if (settings.isOnGoingEnabled(Util.checkPower(mCtx))) {
            if (mCurrentTrack != null) {
                String ar = mCurrentTrack.getArtist();
                String tr = mCurrentTrack.getTrack();
                String api = mCurrentTrack.getMusicAPI().readAPIname();

                // Heart intent
                Intent heartIntent = new Intent(mCtx, ScrobblingService.class);
                heartIntent.setAction(ScrobblingService.ACTION_HEART);
                PendingIntent heartPendingIntent = PendingIntent.getService(mCtx, 0, heartIntent, 0);
                NotificationCompat.Action heartAction = new NotificationCompat.Action.Builder(
                        R.mipmap.ic_status_wail_love_track, "", heartPendingIntent).build();

                Intent targetIntent = new Intent(mCtx, SettingsActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(mCtx, 0, targetIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(mCtx).setContentTitle(tr)
                        .setSmallIcon(R.mipmap.ic_notify).setContentText(ar + " :" + api)
                        .setPriority(NotificationCompat.PRIORITY_MIN).addAction(heartAction)
                        .setContentIntent(contentIntent);

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {
                    builder.setLargeIcon(
                            BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher));
                }

                this.startForeground(14619, builder.build());
                if (!settings.isNotifyEnabled(Util.checkPower(mCtx))) {
                    Intent iNoti = new Intent(mCtx, ForegroundHide.class);
                    this.startService(iNoti);
                }
            }
        } else {
            this.stopForeground(true); // TODO: test if this conflicts/stops scrobbles
        }
    }
}

From source file:com.ayyayo.g.Push.FIRMessagingService.java

private void sendNotification(Map<String, String> data) {

    // handle notification here
    /*//from  ww  w . ja va 2s  .  co m
    * types of notification 1. result update 2. circular update 3. student
    * corner update 4. App custom update 5. Custom Message 6. Notice from
    * College custom
    */
    int num = ++NOTIFICATION_ID;
    Bundle msg = new Bundle();
    for (String key : data.keySet()) {
        Log.e(key, data.get(key));
        msg.putString(key, data.get(key));
    }

    pref = getSharedPreferences("UPDATE_INSTANCE", MODE_PRIVATE);
    edit = pref.edit();
    Intent backIntent;
    Intent intent = null;
    PendingIntent pendingIntent = null;
    backIntent = new Intent(getApplicationContext(), App.class);
    backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    SharedPreferences sp;
    Editor editor;

    switch (Integer.parseInt(msg.getString("type"))) {

    case 1:
        break;
    case 2:

        backIntent = new Intent(getApplicationContext(), DailogeNotice.class);
        backIntent.putExtras(msg);

        stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        // stackBuilder.addParentStack(AppUpdate.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(backIntent);
        pendingIntent = stackBuilder.getPendingIntent(num, PendingIntent.FLAG_UPDATE_CURRENT);

        break;
    case 3:
        backIntent = new Intent(getApplicationContext(), CustomeWebView.class);

        backIntent.putExtras(msg);
        // The stack builder object will contain an artificial back stack
        // for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out
        // of
        // your application to the Home screen.
        stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        // stackBuilder.addParentStack(AppUpdate.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(backIntent);
        pendingIntent = stackBuilder.getPendingIntent(num, PendingIntent.FLAG_UPDATE_CURRENT);

        break;

    case 4:
        backIntent = new Intent(getApplicationContext(), App.class);

        // The stack builder object will contain an artificial back stack
        // for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out
        // of
        // your application to the Home screen.
        stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        // stackBuilder.addParentStack(AppUpdate.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(backIntent);
        pendingIntent = stackBuilder.getPendingIntent(num, PendingIntent.FLAG_UPDATE_CURRENT);

        DatabaseHandler db = new DatabaseHandler(getApplicationContext(), jsonConverter);
        db.addContact(new News(msg.getString("title"), msg.getString("msg"), msg.getString("link"),
                msg.getString("image")), DatabaseHandler.TABLE_NEWS);

        Intent intent_notify = new Intent(FCMActivity.NEW_NOTIFICATION);
        intent_notify.putExtra("DUMMY", "MUST");
        sendBroadcast(intent_notify);
        break;
    default:
        break;
    }
    if (!is_noty) {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setSmallIcon(R.drawable.ic_stat_fcm).setContentTitle(msg.getString("title"))
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg.getString("msg").toString()))
                .setAutoCancel(true).setContentText(msg.getString("msg"));

        if (Integer.parseInt(msg.getString("type")) != 1) {
            mBuilder.setContentIntent(pendingIntent);
        }

        mBuilder.setDefaults(Notification.DEFAULT_ALL);

        mNotificationManager.notify(++NOTIFICATION_ID, mBuilder.build());
    }
}