Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

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

Prototype

int FLAG_CANCEL_CURRENT

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

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:org.wso2.iot.agent.services.AgentStartupReceiver.java

/**
 * Initiates device notifier on device startup.
 * @param context - Application context.
 *///from ww  w.  j av a  2s. co  m
private void setRecurringAlarm(Context context) {
    Resources resources = context.getApplicationContext().getResources();
    String mode = Preference.getString(context, Constants.PreferenceFlag.NOTIFIER_TYPE);
    boolean isLocked = Preference.getBoolean(context, Constants.IS_LOCKED);
    String lockMessage = Preference.getString(context, Constants.LOCK_MESSAGE);

    if (lockMessage == null || lockMessage.isEmpty()) {
        lockMessage = resources.getString(R.string.txt_lock_activity);
    }

    if (isLocked) {
        Operation lockOperation = new Operation();
        lockOperation.setId(DEFAULT_ID);
        lockOperation.setCode(Constants.Operation.DEVICE_LOCK);
        try {
            JSONObject payload = new JSONObject();
            payload.put(Constants.ADMIN_MESSAGE, lockMessage);
            payload.put(Constants.IS_HARD_LOCK_ENABLED, true);
            lockOperation.setPayLoad(payload.toString());
            OperationProcessor operationProcessor = new OperationProcessor(context);
            operationProcessor.doTask(lockOperation);
        } catch (AndroidAgentException e) {
            Log.e(TAG, "Error occurred while executing hard lock operation at the device startup");
        } catch (JSONException e) {
            Log.e(TAG, "Error occurred while building hard lock operation payload");
        }
    }

    int interval = Preference.getInt(context, context.getResources().getString(R.string.shared_pref_frequency));
    if (interval == DEFAULT_INT_VALUE) {
        interval = Constants.DEFAULT_INTERVAL;
    }

    if (mode == null) {
        mode = Constants.NOTIFIER_LOCAL;
    }

    if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED)
            && Constants.NOTIFIER_LOCAL.equals(mode.trim().toUpperCase(Locale.ENGLISH))) {

        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent recurringAlarmIntent = PendingIntent.getBroadcast(context, Constants.DEFAULT_REQUEST_CODE,
                alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, Constants.DEFAULT_START_INTERVAL,
                interval, recurringAlarmIntent);
        Log.i(TAG, "Setting up alarm manager for polling every " + interval + " milliseconds.");
    }
}

From source file:org.qeo.deviceregistration.ui.NotificationHelper.java

private void remoteDeviceFoundNotification(Context context, Intent intent) {
    LOG.fine("(un)publishing notification for remote device");
    List<RegistrationRequest> unregistered = new ArrayList<RegistrationRequest>();
    for (RegistrationRequest req : RemoteDeviceRegistration.getInstance().getUnregisteredDevices()) {
        RegistrationStatusCode status = UnRegisteredDeviceModel.getRegistrationStatus(req.registrationStatus);
        if (status == RegistrationStatusCode.UNREGISTERED) {
            // only add unregistered devices
            unregistered.add(req);/*from   w w w  . ja  va2s .  c  o m*/
        }
    }

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    if (unregistered.isEmpty()) {
        // no more devices in unregistered state, remove notification
        notificationManager.cancel(ServiceApplication.NOTIFICATION_UNREGISTERED_DEVICE_FOUND);
        return;
    }

    // need to create the notification

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.ic_stat_qeo);
    builder.setContentTitle(context.getString(R.string.unregistered_device_notification_title));
    builder.setContentText(context.getString(R.string.unregistered_device_notification_subtitle));
    builder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, ManagementActivity.class);
    resultIntent.putExtra(ManagementActivity.INTENT_EXTRA_START_TAB, ManagementActivity.TAB_DEVICES);
    if (unregistered.size() == 1) {
        // only 1 device
        UnRegisteredDeviceModel device = new UnRegisteredDeviceModel(unregistered.get(0));
        resultIntent.putExtra(UnRegisteredDeviceListFragment.INTENT_EXTRA_DEVICE_TO_REGISTER, device);
    }

    // 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(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
            ServiceApplication.REQUEST_CODE_UNREGISTERED_DEVICE_FOUND, PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(resultPendingIntent);

    // mId allows you to update the notification later on.
    notificationManager.notify(ServiceApplication.NOTIFICATION_UNREGISTERED_DEVICE_FOUND, builder.build());

}

From source file:com.morlunk.leeroy.LeeroyUpdateService.java

private void handleCheckUpdates(Intent intent, boolean notify, ResultReceiver receiver) {
    List<LeeroyApp> appList = LeeroyApp.getApps(getPackageManager());

    if (appList.size() == 0) {
        return;/* w w w .j a  va2 s  .  c o  m*/
    }

    List<LeeroyAppUpdate> updates = new LinkedList<>();
    List<LeeroyApp> notUpdatedApps = new LinkedList<>();
    List<LeeroyException> exceptions = new LinkedList<>();
    for (LeeroyApp app : appList) {
        try {
            String paramUrl = app.getJenkinsUrl() + "/api/json?tree=lastSuccessfulBuild[number,url]";
            URL url = new URL(paramUrl);
            URLConnection conn = url.openConnection();
            Reader reader = new InputStreamReader(conn.getInputStream());

            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.beginObject();
            jsonReader.nextName();
            jsonReader.beginObject();

            int latestSuccessfulBuild = 0;
            String buildUrl = null;
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if ("number".equals(name)) {
                    latestSuccessfulBuild = jsonReader.nextInt();
                } else if ("url".equals(name)) {
                    buildUrl = jsonReader.nextString();
                } else {
                    throw new RuntimeException("Unknown key " + name);
                }
            }
            jsonReader.endObject();
            jsonReader.endObject();
            jsonReader.close();

            if (latestSuccessfulBuild > app.getJenkinsBuild()) {
                LeeroyAppUpdate update = new LeeroyAppUpdate();
                update.app = app;
                update.newBuild = latestSuccessfulBuild;
                update.newBuildUrl = buildUrl;
                updates.add(update);
            } else {
                notUpdatedApps.add(app);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            CharSequence appName = app.getApplicationInfo().loadLabel(getPackageManager());
            exceptions.add(new LeeroyException(app, getString(R.string.invalid_url, appName), e));
        } catch (IOException e) {
            e.printStackTrace();
            exceptions.add(new LeeroyException(app, e));
        }
    }

    if (notify) {
        NotificationManagerCompat nm = NotificationManagerCompat.from(this);
        if (updates.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_update);
            ncb.setTicker(getString(R.string.updates_available));
            ncb.setContentTitle(getString(R.string.updates_available));
            ncb.setContentText(getString(R.string.num_updates, updates.size()));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            Intent appIntent = new Intent(this, AppListActivity.class);
            appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            ncb.setContentIntent(
                    PendingIntent.getActivity(this, 0, appIntent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
            for (LeeroyAppUpdate update : updates) {
                CharSequence appName = update.app.getApplicationInfo().loadLabel(getPackageManager());
                style.addLine(getString(R.string.notify_app_update, appName, update.app.getJenkinsBuild(),
                        update.newBuild));
            }
            style.setSummaryText(getString(R.string.app_name));
            ncb.setStyle(style);
            ncb.setNumber(updates.size());
            nm.notify(NOTIFICATION_UPDATE, ncb.build());
        }

        if (exceptions.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_error);
            ncb.setTicker(getString(R.string.error_checking_updates));
            ncb.setContentTitle(getString(R.string.error_checking_updates));
            ncb.setContentText(getString(R.string.click_to_retry));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            ncb.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            ncb.setNumber(exceptions.size());
            nm.notify(NOTIFICATION_ERROR, ncb.build());
        }
    }

    if (receiver != null) {
        Bundle results = new Bundle();
        results.putParcelableArrayList(EXTRA_UPDATE_LIST, new ArrayList<>(updates));
        results.putParcelableArrayList(EXTRA_NO_UPDATE_LIST, new ArrayList<>(notUpdatedApps));
        results.putParcelableArrayList(EXTRA_EXCEPTION_LIST, new ArrayList<>(exceptions));
        receiver.send(0, results);
    }
}

From source file:com.evandroid.musica.broadcastReceiver.MusicBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /** Google Play Music
     //bool streaming            long position
     //long albumId               String album
     //bool currentSongLoaded      String track
     //long ListPosition         long ListSize
     //long id                  bool playing
     //long duration            int previewPlayType
     //bool supportsRating         int domain
     //bool albumArtFromService      String artist
     //int rating               bool local
     //bool preparing            bool inErrorState
     *//*from www . ja  v  a  2 s  .co m*/

    Bundle extras = intent.getExtras();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true);

    if (extras != null)
        try {
            extras.getInt("state");
        } catch (BadParcelableException e) {
            return;
        }

    if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs
            || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000)
                    || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000)
                    || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200))
            || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000)
                    || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000)
                    || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200)))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") ? extras.getLong("position") : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean("playing", true);

    if (intent.getAction().equals("com.amazon.mp3.metachanged")) {
        artist = extras.getString("com.amazon.mp3.artist");
        track = extras.getString("com.amazon.mp3.track");
    } else if (intent.getAction().equals("com.spotify.music.metadatachanged"))
        isPlaying = spotifyPlaying;
    else if (intent.getAction().equals("com.spotify.music.playbackstatechanged"))
        spotifyPlaying = isPlaying;

    if ((artist == null || "".equals(artist)) //Could be problematic
            || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts
        return;

    SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    String currentArtist = current.getString("artist", "");
    String currentTrack = current.getString("track", "");

    SharedPreferences.Editor editor = current.edit();
    editor.putString("artist", artist);
    editor.putString("track", track);
    editor.putLong("position", position);
    editor.putBoolean("playing", isPlaying);
    if (isPlaying) {
        long currentTime = System.currentTimeMillis();
        editor.putLong("startTime", currentTime);
    }
    editor.apply();

    autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false);
    int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0"));

    if (autoUpdate && App.isActivityVisible()) {
        Intent internalIntent = new Intent("Broadcast");
        internalIntent.putExtra("artist", artist).putExtra("track", track);
        LyricsViewFragment.sendIntent(context, internalIntent);
        forceAutoUpdate(false);
    }

    SQLiteDatabase db = new DatabaseHelper(context).getReadableDatabase();
    boolean inDatabase = DatabaseHelper.presenceCheck(db, new String[] { artist, track, artist, track });
    db.close();

    if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) {
        Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS",
                new String[] { artist, track });
        Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist)
                .putExtra("track", track);
        PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch,
                context.getString(R.string.wearable_prompt), wearablePending).build();

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
        NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context);

        if ("0".equals(sharedPref.getString("pref_theme", "0")))
            notifBuilder.setColor(context.getResources().getColor(R.color.primary));

        notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setGroupSummary(true);

        wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setOngoing(false).setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
        } else
            notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW

        Notification notif = notifBuilder.build();
        Notification wearableNotif = wearableNotifBuilder.build();

        if (notificationPref == 2)
            notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        else
            notif.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat.from(context).notify(0, notif);
        try {
            context.getPackageManager().getPackageInfo("com.google.android.wearable.app",
                    PackageManager.GET_META_DATA);
            NotificationManagerCompat.from(context).notify(8, wearableNotif);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    } else if (track.equals(current.getString("track", "")))
        NotificationManagerCompat.from(context).cancel(0);
}

From source file:net.kourlas.voipms_sms.Notifications.java

public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
        Conversation[] conversations = Database.getInstance(applicationContext)
                .getConversations(preferences.getDid());
        for (Conversation conversation : conversations) {
            if (!conversation.isUnread() || !contacts.contains(conversation.getContact())
                    || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                            && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                                    .getContact().equals(conversation.getContact()))) {
                continue;
            }//  ww  w . j  a v  a  2 s. c  om

            String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
            if (smsContact == null) {
                smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
            }

            String allSmses = "";
            String mostRecentSms = "";
            boolean initial = true;
            for (Message message : conversation.getMessages()) {
                if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
                    if (initial) {
                        allSmses = message.getText();
                        mostRecentSms = message.getText();
                        initial = false;
                    } else {
                        allSmses = message.getText() + "\n" + allSmses;
                    }
                } else {
                    break;
                }
            }

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext);

            notificationBuilder.setContentTitle(smsContact);
            notificationBuilder.setContentText(mostRecentSms);
            notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
            notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
            notificationBuilder
                    .setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
            notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
            if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
                notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
            } else {
                notificationBuilder.setVibrate(new long[] { 0 });
            }
            notificationBuilder.setColor(0xFFAA0000);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

            Bitmap largeIconBitmap;
            try {
                largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                        Uri.parse(Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
                largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
                largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
                notificationBuilder.setLargeIcon(largeIconBitmap);
            } catch (Exception ignored) {

            }

            Intent intent = new Intent(applicationContext, ConversationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
            stackBuilder.addParentStack(ConversationActivity.class);
            stackBuilder.addNextIntent(intent);
            notificationBuilder
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

            Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
            } else {
                //noinspection deprecation
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            }
            replyIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent replyPendingIntent = PendingIntent.getActivity(applicationContext, 0, replyIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_reply_white_24dp,
                    applicationContext.getString(R.string.notifications_button_reply), replyPendingIntent);
            notificationBuilder.addAction(replyAction.build());

            Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
            markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast(applicationContext, 0,
                    markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_drafts_white_24dp,
                    applicationContext.getString(R.string.notifications_button_mark_read),
                    markAsReadPendingIntent);
            notificationBuilder.addAction(markAsReadAction.build());

            int id;
            if (notificationIds.get(conversation.getContact()) != null) {
                id = notificationIds.get(conversation.getContact());
            } else {
                id = notificationIdCount++;
                notificationIds.put(conversation.getContact(), id);
            }
            NotificationManager notificationManager = (NotificationManager) applicationContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}

From source file:com.devbrackets.android.exomedia.EMLockScreen.java

private PendingIntent getMediaButtonReceiverPendingIntent(ComponentName componentName) {
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(componentName);

    mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, mediaServiceClass.getName());
    return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.marianhello.cordova.bgloc.LocationUpdateService.java

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

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        // Stop-detection PI
        stationaryAlarmPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_ALARM_ACTION), 0);
        registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION));

        // Stationary region PI
        stationaryRegionPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_REGION_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION));

        // Stationary location monitor PI
        stationaryLocationPollingPI = PendingIntent.getBroadcast(this, 0,
                new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0);
        registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION));

        // One-shot PI (TODO currently unused)
        singleUpdatePI = PendingIntent.getBroadcast(this, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));

        /////*from w w  w .  j a  va2s  .  c  o m*/
        // DISABLED
        // Listen to Cell-tower switches (NOTE does not operate while suspended)
        //telephonyManager.listen(phoneStateListener, LISTEN_CELL_LOCATION);
        //

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        wakeLock.acquire();

        // Location criteria
        criteria = new Criteria();
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
    }

From source file:ca.etsmtl.applets.etsmobile.NewsListActivity.java

private void setAlarm() {
    final Intent toAlarm = new Intent(this, NewsAlarmReceiver.class);
    final PendingIntent toDownload = PendingIntent.getBroadcast(this, 0, toAlarm,
            PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    final Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));

    updateTime.set(Calendar.HOUR_OF_DAY, 6);
    updateTime.set(Calendar.MINUTE, 00);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);/*from w  w  w  .j a va 2 s  .co  m*/

    updateTime.set(Calendar.HOUR_OF_DAY, 12);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);

    updateTime.set(Calendar.HOUR_OF_DAY, 18);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);
}

From source file:com.gmail.at.faint545.fragments.QueueFragment.java

private void setRecurringAlarm() {
    if (getRemote().getRefreshInterval() != -1) {
        updateTime = Calendar.getInstance();
        updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
        updateTime.set(Calendar.MINUTE, 1);

        Intent downloader = new Intent(getActivity(), AlarmReciever.class);
        downloader.putExtra("url", getRemote().buildURL());
        downloader.putExtra("api", getRemote().getApiKey());
        downloader.putExtra("messenger", new Messenger(handler));

        PendingIntent recurringDownload = PendingIntent.getBroadcast(getActivity(), 0, downloader,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager alarms = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(),
                getRemote().getRefreshInterval(), recurringDownload);
    } else {/*from w ww.  j a v a 2 s . c  o  m*/
        downloadQueue(null);
    }
}

From source file:vrisini.cordova.plugin.schedule.Schedule.java

/**
 * Cancel a specific notification that was previously registered.
 *
 * @param notificationId/*from   w  ww. ja v  a  2s .c om*/
 *            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, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = getAlarmManager();
    NotificationManager nc = getNotificationManager();

    am.cancel(pi);

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

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