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:app.jorge.mobile.com.transportalert.ScrollingActivity.java

public void scheduleAlarm() {
    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Setup periodic alarm every 5 seconds
    long firstMillis = System.currentTimeMillis(); // alarm is set right away
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY

    //alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
    //      AlarmManager.INTERVAL_HALF_HOUR, pIntent);

    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, AlarmManager.INTERVAL_HALF_HOUR, pIntent);
}

From source file:ca.zadrox.dota2esportticker.service.ReminderAlarmService.java

private void cancelAlarm(final long matchId, final long matchStart) {
    final long currentTime = TimeUtils.getUTCTime();

    LOGD(TAG, "Unscheduling Alarm");

    if (currentTime > matchStart) {
        LOGD(TAG, "wat.");
        return;//from   w w w  . j  a va 2 s  .  co m
    }

    final Intent notifIntent = new Intent(ACTION_NOTIFY_MATCH, null, this, ReminderAlarmService.class);

    notifIntent.setData(
            new Uri.Builder().authority("ca.zadrox.dota2esportticker").path(String.valueOf(matchId)).build());

    notifIntent.putExtra(ReminderAlarmService.EXTRA_MATCH_ID, matchId);
    notifIntent.putExtra(ReminderAlarmService.EXTRA_MATCH_START, matchStart);

    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    final AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

    am.cancel(pi);
}

From source file:com.androcast.illusion.illusionmod.services.BootService.java

private void init() {
    final List<String> applys = new ArrayList<>();
    final List<String> plugins = new ArrayList<>();

    Class[] classes = { BatteryFragment.class, CPUFragment.class, CPUHotplugFragment.class,
            CPUVoltageFragment.class, EntropyFragment.class, GPUFragment.class, IOFragment.class,
            KSMFragment.class, LMKFragment.class, MiscFragment.class, ScreenFragment.class, SoundFragment.class,
            ThermalFragment.class, VMFragment.class, WakeFragment.class };

    for (Class mClass : classes)
        if (Utils.getBoolean(mClass.getSimpleName() + "onboot", false, this)) {
            log("Applying on boot for " + mClass.getSimpleName());
            applys.addAll(Utils.getApplys(mClass));
        }/*  w  w w.j a  va2  s  . c  om*/

    String plugs;
    if (!(plugs = Utils.getString("plugins", "", this)).isEmpty()) {
        String[] ps = plugs.split("wefewfewwgwe");
        for (String plug : ps)
            if (Utils.getBoolean(plug + "onboot", false, this))
                plugins.add(plug);
    }

    if (applys.size() > 0 || plugins.size() > 0) {
        final int delay = Utils.getInt("applyonbootdelay", 5, this);
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle(getString(R.string.apply_on_boot))
                .setContentText(getString(R.string.apply_on_boot_time, delay))
                .setSmallIcon(R.drawable.ic_launcher);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean notification = Utils.getBoolean("applyonbootnotification", true, BootService.this);
                for (int i = delay; i >= 0; i--)
                    try {
                        Thread.sleep(1000);
                        String note = getString(R.string.apply_on_boot_time, i);
                        if (notification) {
                            mBuilder.setContentText(note).setProgress(delay, delay - i, false);
                            mNotifyManager.notify(id, mBuilder.build());
                        } else if ((i % 10 == 0 || i == delay) && i != 0)
                            toast(note);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                if (notification) {
                    mBuilder.setContentText(getString(R.string.apply_on_boot_finished)).setProgress(0, 0,
                            false);
                    mNotifyManager.notify(id, mBuilder.build());
                }
                apply(applys, plugins);
                stopSelf();
            }
        }).start();
    } else
        stopSelf();
}

From source file:net.olejon.mdapp.MessageIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final Context mContext = this;

    final MyTools mTools = new MyTools(mContext);

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    int projectVersionCode = mTools.getProjectVersionCode();

    String device = mTools.getDevice();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/message/?version_code=" + projectVersionCode
                    + "&device=" + device,
            new Response.Listener<JSONObject>() {
                @SuppressLint("InlinedApi")
                @Override//from   w  w w  .  ja  va  2 s  .com
                public void onResponse(JSONObject response) {
                    try {
                        final long id = response.getLong("id");
                        final String title = response.getString("title");
                        final String message = response.getString("message");
                        final String bigMessage = response.getString("big_message");
                        final String button = response.getString("button");
                        final String uri = response.getString("uri");

                        final long lastId = mTools.getSharedPreferencesLong("MESSAGE_LAST_ID");

                        mTools.setSharedPreferencesLong("MESSAGE_LAST_ID", id);

                        if (lastId != 0 && id != lastId) {
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                    R.drawable.ic_launcher);

                            NotificationManagerCompat notificationManager = NotificationManagerCompat
                                    .from(mContext);
                            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                    mContext);

                            notificationBuilder.setWhen(mTools.getCurrentTime()).setAutoCancel(true)
                                    .setPriority(Notification.PRIORITY_HIGH)
                                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                                    .setCategory(Notification.CATEGORY_MESSAGE).setLargeIcon(bitmap)
                                    .setSmallIcon(R.drawable.ic_local_hospital_white_24dp)
                                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                    .setLights(Color.BLUE, 1000, 2000).setTicker(message).setContentTitle(title)
                                    .setContentText(message)
                                    .setStyle(new NotificationCompat.BigTextStyle().bigText(bigMessage));

                            if (!uri.equals("")) {
                                Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                PendingIntent launchPendingIntent = PendingIntent.getActivity(mContext, 0,
                                        launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                                notificationBuilder.setContentIntent(launchPendingIntent).addAction(
                                        R.drawable.ic_local_hospital_white_24dp, button, launchPendingIntent);
                            }

                            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
                        }
                    } catch (Exception e) {
                        Log.e("MessageIntentService", Log.getStackTraceString(e));
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("MessageIntentService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:com.example.android.wearable.mjpegviewwear.MainActivity.java

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

    LOGD(TAG, "onCreate");
    setContentView(R.layout.main_activity);

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.app_name)).setContentText(getString(R.string.running))
            .setOngoing(true);/*from   ww w.j a  va  2s . c  om*/
    Intent resultIntent = new Intent(this, MainActivity.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();

    // for MJPEG View
    SharedPreferences preferences = getSharedPreferences("SAVED_VALUES", MODE_PRIVATE);
    mWidth = preferences.getInt("width", mWidth);
    mHeight = preferences.getInt("height", mHeight);
    mIp_ad1 = preferences.getInt("ip_ad1", mIp_ad1);
    mIp_ad2 = preferences.getInt("ip_ad2", mIp_ad2);
    mIp_ad3 = preferences.getInt("ip_ad3", mIp_ad3);
    mIp_ad4 = preferences.getInt("ip_ad4", mIp_ad4);
    mIp_port = preferences.getInt("ip_port", mIp_port);
    mIp_command = preferences.getString("ip_command", mIp_command);
    mFrameSkip = preferences.getInt("frameSkip", mFrameSkip);

    StringBuilder sb = new StringBuilder();
    String s_http = "http://";
    String s_dot = ".";
    String s_colon = ":";
    String s_slash = "/";
    sb.append(s_http);
    sb.append(mIp_ad1);
    sb.append(s_dot);
    sb.append(mIp_ad2);
    sb.append(s_dot);
    sb.append(mIp_ad3);
    sb.append(s_dot);
    sb.append(mIp_ad4);
    sb.append(s_colon);
    sb.append(mIp_port);
    sb.append(s_slash);
    sb.append(mIp_command);
    mURL = new String(sb);

    mMv = (MjpegView) findViewById(R.id.mv);
    if (mMv != null) {
        mMv.setResolution(mWidth, mHeight);
        mMv.setFrameSkip(mFrameSkip);
    }

    setTitle(R.string.title_connecting);
    new DoRead().execute(mURL);
}

From source file:com.actinarium.rhythm.control.RhythmNotificationService.java

private void handleShowNotification(int notificationId) {
    Application application = getApplication();
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification notification;/* ww w  .  j  a  v  a  2s .  c  o  m*/

    // If the application is not the host - show error and return.
    if (!(application instanceof RhythmControl.Host)) {
        notification = makeCommonNotification(getString(R.string.arl_no_host_text))
                .setColor(NOTIFICATION_ERROR_COLOR).setContentTitle(getString(R.string.arl_no_host_title))
                .build();
        manager.notify(notificationId, notification);
        return;
    }

    RhythmControl control = ((RhythmControl.Host) application).getRhythmControl();
    RhythmGroup currentGroup = control.getCurrentNotificationGroup();

    // If there are no groups yet - show warning and return.
    if (currentGroup == null) {
        notification = makeCommonNotification(getString(R.string.arl_no_groups_text))
                .setColor(NOTIFICATION_ERROR_COLOR).setContentTitle(getString(R.string.arl_no_groups_title))
                .build();
        manager.notify(notificationId, notification);
        return;
    }

    // Now if everything is OK:
    Intent nextGroupAction = new Intent(this, RhythmNotificationService.class);
    nextGroupAction.setAction(ACTION_NEXT_GROUP);
    PendingIntent piNextGroupAction = PendingIntent.getService(this, 0, nextGroupAction,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent nextOverlayAction = new Intent(this, RhythmNotificationService.class);
    nextOverlayAction.setAction(ACTION_NEXT_OVERLAY);
    PendingIntent piNextOverlayAction = PendingIntent.getService(this, 0, nextOverlayAction,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent dismissAction = new Intent(this, RhythmNotificationService.class);
    dismissAction.setAction(ACTION_DISMISS_QUICK_CONTROL);
    PendingIntent piDismissAction = PendingIntent.getService(this, 0, dismissAction,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // todo: another action when notification is clicked (control activity will be added in v1.0)

    // Determine what to write in notification
    RhythmOverlay currentOverlay = currentGroup.getCurrentOverlay();
    String groupText = getString(R.string.arl_group, currentGroup.toString());
    String overlayText = currentOverlay == null ? getString(R.string.arl_no_overlay)
            : getString(R.string.arl_overlay, currentOverlay.toString());

    // Finally, build and display the notification
    notification = makeCommonNotification(overlayText).setColor(NOTIFICATION_ICON_COLOR)
            .setContentTitle(groupText).setDeleteIntent(piDismissAction)
            .addAction(new NotificationCompat.Action(R.drawable.arl_loop, getString(R.string.arl_next_group),
                    piNextGroupAction))
            .addAction(new NotificationCompat.Action(R.drawable.arl_loop, getString(R.string.arl_next_overlay),
                    piNextOverlayAction))
            .build();
    manager.notify(notificationId, notification);
}

From source file:com.imobilize.blogposts.gcmnotifications.GcmIntentService.java

private void sendNotification(String articleDataString) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    JSONObject articleDataJson = null;//from www  .java2  s.  com
    try {
        articleDataJson = new JSONObject(articleDataString);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    Intent intentForArticleActivity = new Intent(this, ArticleActivity.class);

    String notificationMessage = null;
    try {
        intentForArticleActivity.putExtra(Constants.ARTICLE_TITLE, articleDataJson.getString("title"));
        intentForArticleActivity.putExtra(Constants.ARTICLE_METADATA, "Posted by "
                + articleDataJson.getString("author") + " on " + articleDataJson.getString("creationDate"));
        intentForArticleActivity.putExtra(Constants.ARTICLE_CONTENT, articleDataJson.getString("content"));
        intentForArticleActivity.putExtra(Constants.ARTICLE_KEY, articleDataJson.getString("key"));
        notificationMessage = "Read our new article from category " + articleDataJson.getString("categories")
                + " called '" + articleDataJson.getString("title") + "'";

    } catch (JSONException e) {
        e.printStackTrace();
    }
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intentForArticleActivity,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_gcm)
            .setAutoCancel(true).setContentTitle("BLOGPOSTS")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage))
            .setContentText(notificationMessage);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:com.iniciacomunicacion.devicenotification.DeviceNotification.java

/**
 * Adds notification/*from   w w w .j a  v a  2 s .c  o  m*/
 * 
 * @param callbackContext, Callback context of the request from Cordova
 * @param title, The title of notification
 * @param message, The content text of the notification
 * @param Id, The unique ID of the notification
 * @param seconds
 */
public void add(CallbackContext callbackContext, String ticker, String title, String message, int id) {

    Resources res = DeviceNotification.context.getResources();
    int ic_launcher = res.getIdentifier("icon", "drawable", cordova.getActivity().getPackageName());

    /* Version 4.x
    NotificationManager notificationManager = (NotificationManager)DeviceNotification.activity.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification.Builder(DeviceNotification.Context)
    .setTicker(ticker)
    .setContentTitle(title)
    .setContentText(message)
    .setSmallIcon(ic_launcher)
    .setWhen(System.currentTimeMillis())
    .setAutoCancel(true)
    .build();
    notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
    notificationManager.notify(id, notification);*/

    //Version 2.x
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(DeviceNotification.activity)
            .setSmallIcon(ic_launcher).setWhen(System.currentTimeMillis()).setContentTitle(title)
            .setContentText(message).setTicker(ticker);
    Intent resultIntent = new Intent(DeviceNotification.activity, DeviceNotification.activity.getClass());
    PendingIntent resultPendingIntent = PendingIntent.getActivity(DeviceNotification.activity, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotifyMgr = (NotificationManager) DeviceNotification.activity
            .getSystemService(android.content.Context.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(id, mBuilder.build());
}

From source file:com.amaze.filemanager.asynchronous.services.ZipService.java

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    String mZipPath = intent.getStringExtra(KEY_COMPRESS_PATH);

    ArrayList<HybridFileParcelable> baseFiles = intent.getParcelableArrayListExtra(KEY_COMPRESS_FILES);

    File zipFile = new File(mZipPath);

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

    if (!zipFile.exists()) {
        try {/*from www.  j av a 2 s  .c o m*/
            zipFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    accentColor = ((AppConfig) getApplication()).getUtilsProvider().getColorPreference()
            .getCurrentUserColorPreferences(this, sharedPreferences).accent;

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    customSmallContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_small);
    customBigContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_big);

    Intent stopIntent = new Intent(KEY_COMPRESS_BROADCAST_CANCEL);
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1234, stopIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action action = new NotificationCompat.Action(R.drawable.ic_zip_box_grey600_36dp,
            getString(R.string.stop_ftp), stopPendingIntent);

    mBuilder = new NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID)
            .setSmallIcon(R.drawable.ic_zip_box_grey600_36dp).setContentIntent(pendingIntent)
            .setCustomContentView(customSmallContentViews).setCustomBigContentView(customBigContentViews)
            .setCustomHeadsUpContentView(customSmallContentViews)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle()).addAction(action).setOngoing(true)
            .setColor(accentColor);

    NotificationConstants.setMetadata(this, mBuilder, NotificationConstants.TYPE_NORMAL);
    startForeground(NotificationConstants.ZIP_ID, mBuilder.build());
    initNotificationViews();

    super.onStartCommand(intent, flags, startId);
    super.progressHalted();
    asyncTask = new CompressAsyncTask(this, baseFiles, mZipPath);
    asyncTask.execute();
    // If we get killed, after returning from here, restart
    return START_STICKY;
}

From source file:at.aec.solutions.checkmkagent.AgentService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.v(TAG, "onCreate");

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    m_wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
    m_wakeLock.acquire();//from   w ww . java 2s  .c o  m

    //Copy busybox binary to app directory
    if (!PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("bbinstalled",
            false)) {
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
                .putBoolean("bbinstalled", true).commit();

        // There is also String[] Build.SUPPORTED_ABIS from API 21 on and
        // before String Build.CPU_ABI String Build.CPU_ABI2, maybe i should investigate there
        String arch = System.getProperty("os.arch");
        Log.v(TAG, arch);
        if (arch.equals("armv7l")) {
            copyAsset(getAssets(), "bbb/busybox", getApplicationInfo().dataDir + "/busybox");
        }
        if (arch.equals("i686")) {
            copyAsset(getAssets(), "bbb/busybox-i686", getApplicationInfo().dataDir + "/busybox");
        }

        //         copyAsset(getAssets(), "bbb/busybox-x86_64", getApplicationInfo().dataDir+"/busybox-x86_64");
        changeBusyboxPermission();
    }

    socketServerThread = new Thread(new SocketServerThread());
    socketServerThread.setName("CheckMK-Agent ServerThread");
    socketServerThread.start();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("CheckMK Agent started.")
            .setContentText("Listening on Port " + SERVERPORT + ". Tap to configure.");

    Intent resultIntent = new Intent(this, ConfigureActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ConfigureActivity.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) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    Notification notify = mBuilder.build();
    notify.flags |= Notification.FLAG_NO_CLEAR;

    mNotificationManager.notify(mId, notify);
}