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.onebusaway.android.directions.realtime.RealtimeService.java

private void showNotification(ItineraryDescription description, int title, int message,
        Class<? extends Activity> notificationTarget, Bundle params, List<Itinerary> itineraries) {

    String titleText = getResources().getString(title);
    String messageText = getResources().getString(message);

    Intent openIntent = new Intent(getApplicationContext(), notificationTarget);
    openIntent.putExtras(params);/* ww  w .  ja v  a2  s .co m*/
    openIntent.putExtra(OTPConstants.INTENT_SOURCE, OTPConstants.Source.NOTIFICATION);
    openIntent.putExtra(OTPConstants.ITINERARIES, (ArrayList<Itinerary>) itineraries);
    openIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent openPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, openIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.drawable.ic_stat_notification).setContentTitle(titleText)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(messageText)).setContentText(messageText)
            .setPriority(NotificationCompat.PRIORITY_MAX).setContentIntent(openPendingIntent);

    NotificationManager notificationManager = (NotificationManager) getApplicationContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = mBuilder.build();
    notification.defaults = Notification.DEFAULT_ALL;
    notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;

    Integer notificationId = description.getId();
    notificationManager.notify(notificationId, notification);
}

From source file:com.appdevper.mediaplayer.app.MediaNotificationManager.java

private PendingIntent createContentIntent(MediaDescriptionCompat description) {
    Intent openUI = new Intent(mService, MainActivity.class);
    openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    openUI.putExtra(MainActivity.EXTRA_START_FULLSCREEN, true);
    if (description != null) {
        openUI.putExtra(MainActivity.EXTRA_CURRENT_MEDIA_DESCRIPTION, description);
    }/*from ww w . jav  a2s. c om*/
    return PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.marianhello.bgloc.LocationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    log.info("Received start startId: {} intent: {}", startId, intent);

    if (provider != null) {
        provider.onDestroy();/*from  w ww  . ja  v a2s .c o  m*/
    }

    if (intent == null) {
        //service has been probably restarted so we need to load config from db
        ConfigurationDAO dao = DAOFactory.createConfigurationDAO(this);
        try {
            config = dao.retrieveConfiguration();
        } catch (JSONException e) {
            log.error("Config exception: {}", e.getMessage());
            config = new Config(); //using default config
        }
    } else {
        if (intent.hasExtra("config")) {
            config = intent.getParcelableExtra("config");
        } else {
            config = new Config(); //using default config
        }
    }

    log.debug("Will start service with: {}", config.toString());

    LocationProviderFactory spf = new LocationProviderFactory(this);
    provider = spf.getInstance(config.getLocationProvider());

    if (config.getStartForeground()) {
        // Build a Notification required for running service in foreground.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(config.getNotificationTitle());
        builder.setContentText(config.getNotificationText());
        if (config.getSmallNotificationIcon() != null) {
            builder.setSmallIcon(getDrawableResource(config.getSmallNotificationIcon()));
        } else {
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
        }
        if (config.getLargeNotificationIcon() != null) {
            builder.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),
                    getDrawableResource(config.getLargeNotificationIcon())));
        }
        if (config.getNotificationIconColor() != null) {
            builder.setColor(this.parseNotificationIconColor(config.getNotificationIconColor()));
        }

        // Add an onclick handler to the notification
        Context context = getApplicationContext();
        String packageName = context.getPackageName();
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE
                | Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
    }

    provider.startRecording();

    //We want this service to continue running until it is explicitly stopped
    return START_STICKY;
}

From source file:com.salesforce.marketingcloud.android.demoapp.LearningAppApplication.java

@Override
public NotificationCompat.Builder setupNotificationBuilder(@NonNull Context context,
        @NonNull NotificationMessage notificationMessage) {
    NotificationCompat.Builder builder = NotificationManager.getDefaultNotificationBuilder(context,
            notificationMessage, NotificationManager.createDefaultNotificationChannel(context),
            R.drawable.ic_stat_app_logo_transparent);

    Map<String, String> customKeys = notificationMessage.customKeys();
    if (!customKeys.containsKey("category") || !customKeys.containsKey("sale_date")) {
        return builder;
    }//w  w w . j av a2  s . c  om

    if ("sale".equalsIgnoreCase(customKeys.get("category"))) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        simpleDateFormat.setTimeZone(TimeZone.getDefault());
        try {
            Date saleDate = simpleDateFormat.parse(customKeys.get("sale_date"));
            Intent intent = new Intent(Intent.ACTION_INSERT).setData(CalendarContract.Events.CONTENT_URI)
                    .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, saleDate.getTime())
                    .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, saleDate.getTime())
                    .putExtra(CalendarContract.Events.TITLE, customKeys.get("event_title"))
                    .putExtra(CalendarContract.Events.DESCRIPTION, customKeys.get("alert"))
                    .putExtra(CalendarContract.Events.HAS_ALARM, 1)
                    .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
            PendingIntent pendingIntent = PendingIntent.getActivity(context,
                    R.id.interactive_notification_reminder, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.addAction(android.R.drawable.ic_menu_my_calendar, getString(R.string.in_btn_add_reminder),
                    pendingIntent);
        } catch (ParseException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
    return builder;
}

From source file:com.allthatseries.RNAudioPlayer.MediaNotificationManager.java

private PendingIntent createContentIntent(Class activityClass) {
    Intent openUI = new Intent(mService, activityClass);
    openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    return PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:org.restcomm.app.qoslib.Services.TrackingManager.java

public void startCoverageTracking() {
    bTracking = true;/*from  ww  w.j a v a  2s.  c o  m*/
    this.owner.keepAwake(true, true);
    AlarmManager alarmMgr = (AlarmManager) owner.getSystemService(Service.ALARM_SERVICE);
    Intent intent = new Intent(IntentHandler.ACTION_TRACKING_5MINUTE);
    PendingIntent alarm = PendingIntent.getBroadcast(owner, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmMgr.cancel(alarm);
    //trackingExpires = System.currentTimeMillis() + (numFiveMinutePeriods) * 5L * 60L * 1000L;

    //PreferenceManager.getDefaultSharedPreferences(owner).edit().putLong(PreferenceKeys.Miscellaneous.TRACKING_EXPIRES, trackingExpires).commit();
    long expiresTime = System.currentTimeMillis() + (durMinutes * 60 - trackingElapsed) * 1000;
    PreferenceManager.getDefaultSharedPreferences(owner).edit()
            .putLong(PreferenceKeys.Miscellaneous.ENGINEER_MODE_EXPIRES_TIME, expiresTime).commit();

    long delay = 0;
    if (durMinutes == 0) // continuous tracking
    {
        //trackingExpires = 0;
        // store a tracking expiry date of 10 million seconds from now
        //PreferenceManager.getDefaultSharedPreferences(owner).edit().putLong(PreferenceKeys.Miscellaneous.TRACKING_EXPIRES, System.currentTimeMillis()+10000000000l).commit();
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putLong(PreferenceKeys.Miscellaneous.ENGINEER_MODE_EXPIRES_TIME, System.currentTimeMillis())
                .commit();
    }
    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "startTracking",
            "durationMinutes=" + durMinutes + ",covInterval=" + coverageInterval + ",SpeedInterval="
                    + speedtestInterval + ",videoInterval=" + videoInterval);

    delay = 5L * 60L * 1000L;
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, delay, alarm);
}

From source file:com.meetingcpp.sched.gcm.command.NotificationCommand.java

private void processCommand(Context context, NotificationCommandModel command) {
    // Check format
    if (!"1.0.00".equals(command.format)) {
        LOGW(TAG, "GCM notification command has unrecognized format: " + command.format);
        return;/*from ww  w.j a v  a 2s . c  o  m*/
    }

    // Check app version
    if (!TextUtils.isEmpty(command.minVersion) || !TextUtils.isEmpty(command.maxVersion)) {
        LOGD(TAG, "Command has version range.");
        int minVersion = 0;
        int maxVersion = Integer.MAX_VALUE;
        try {
            if (!TextUtils.isEmpty(command.minVersion)) {
                minVersion = Integer.parseInt(command.minVersion);
            }
            if (!TextUtils.isEmpty(command.maxVersion)) {
                maxVersion = Integer.parseInt(command.maxVersion);
            }
            LOGD(TAG, "Version range: " + minVersion + " - " + maxVersion);
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            LOGD(TAG, "My version code: " + pinfo.versionCode);
            if (pinfo.versionCode < minVersion) {
                LOGD(TAG, "Skipping command because our version is too old, " + pinfo.versionCode + " < "
                        + minVersion);
                return;
            }
            if (pinfo.versionCode > maxVersion) {
                LOGD(TAG, "Skipping command because our version is too new, " + pinfo.versionCode + " > "
                        + maxVersion);
                return;
            }
        } catch (NumberFormatException ex) {
            LOGE(TAG,
                    "Version spec badly formatted: min=" + command.minVersion + ", max=" + command.maxVersion);
            return;
        } catch (Exception ex) {
            LOGE(TAG, "Unexpected problem doing version check.", ex);
            return;
        }
    }

    // Check if we are the right audience
    LOGD(TAG, "Checking audience: " + command.audience);
    if ("remote".equals(command.audience)) {
        if (SettingsUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is remote).");
        }
    } else if ("local".equals(command.audience)) {
        if (!SettingsUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is local).");
        }
    } else if ("all".equals(command.audience)) {
        LOGD(TAG, "Relevant (audience is 'all').");
    } else {
        LOGE(TAG, "Invalid audience on GCM notification command: " + command.audience);
        return;
    }

    // Check if it expired
    Date expiry = command.expiry == null ? null : TimeUtils.parseTimestamp(command.expiry);
    if (expiry == null) {
        LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry);
        return;
    } else if (expiry.getTime() < UIUtils.getCurrentTime(context)) {
        LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString());
        return;
    } else {
        LOGD(TAG, "Message is still valid (expiry is in the future: " + expiry.toString() + ")");
    }

    // decide the intent that will be fired when the user clicks the notification
    Intent intent;
    if (TextUtils.isEmpty(command.dialogText)) {
        // notification leads directly to the URL, no dialog
        if (TextUtils.isEmpty(command.url)) {
            intent = new Intent(context, MyScheduleActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(command.url));
        }
    } else {
        // use a dialog
        intent = new Intent(context, MyScheduleActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_TITLE,
                command.dialogTitle == null ? "" : command.dialogTitle);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_MESSAGE,
                command.dialogText == null ? "" : command.dialogText);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_YES,
                command.dialogYes == null ? "OK" : command.dialogYes);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_NO, command.dialogNo == null ? "" : command.dialogNo);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_URL, command.url == null ? "" : command.url);
    }

    final String title = TextUtils.isEmpty(command.title) ? context.getString(R.string.app_name)
            : command.title;
    final String message = TextUtils.isEmpty(command.message) ? "" : command.message;

    // fire the notification
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
            new NotificationCompat.Builder(context).setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_stat_notification).setTicker(command.message)
                    .setContentTitle(title).setContentText(message)
                    //.setColor(context.getResources().getColor(R.color.theme_primary))
                    // Note: setColor() is available in the support lib v21+.
                    // We commented it out because we want the source to compile
                    // against support lib v20. If you are using support lib
                    // v21 or above on Android L, uncomment this line.
                    .setContentIntent(
                            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))
                    .setAutoCancel(true).build());
}

From source file:com.pluscubed.velociraptor.settings.SettingsActivity.java

@SuppressWarnings("ConstantConditions")
@Override/*  w w  w  .  j ava 2 s  .c  o m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    ButterKnife.bind(this);

    setSupportActionBar(toolbar);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        View marshmallowPermissionsCard = findViewById(R.id.card_m_permissions);
        marshmallowPermissionsCard.setVisibility(View.GONE);
    }

    openStreetMapView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ShareCompat.IntentBuilder.from(SettingsActivity.this).setText("https://www.openstreetmap.org")
                    .setType("text/plain").startChooser();
        }
    });

    checkCoverageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleApiClient = new GoogleApiClient.Builder(SettingsActivity.this)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        @SuppressWarnings("MissingPermission")
                        public void onConnected(@Nullable Bundle bundle) {
                            String uriString = "http://product.itoworld.com/map/124";
                            if (Utils.isLocationPermissionGranted(SettingsActivity.this)) {
                                Location lastLocation = LocationServices.FusedLocationApi
                                        .getLastLocation(googleApiClient);
                                if (lastLocation != null) {
                                    uriString += "?lon=" + lastLocation.getLongitude() + "&lat="
                                            + lastLocation.getLatitude() + "&zoom=12";
                                }
                            }
                            Intent intent = new Intent();
                            intent.setData(Uri.parse(uriString));
                            intent.setAction(Intent.ACTION_VIEW);
                            try {
                                startActivity(intent);
                            } catch (ActivityNotFoundException e) {
                                Snackbar.make(enableFloatingButton, R.string.open_coverage_map_failed,
                                        Snackbar.LENGTH_LONG).show();
                            }

                            googleApiClient.disconnect();
                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                        }
                    }).addApi(LocationServices.API).build();

            googleApiClient.connect();
        }
    });

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notifControlsContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SettingsActivity.this, SpeedLimitService.class);
            intent.putExtra(SpeedLimitService.EXTRA_NOTIF_START, true);
            PendingIntent pending = PendingIntent.getService(SettingsActivity.this, PENDING_SERVICE, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Intent intentClose = new Intent(SettingsActivity.this, SpeedLimitService.class);
            intentClose.putExtra(SpeedLimitService.EXTRA_NOTIF_CLOSE, true);
            PendingIntent pendingClose = PendingIntent.getService(SettingsActivity.this, PENDING_SERVICE_CLOSE,
                    intentClose, PendingIntent.FLAG_CANCEL_CURRENT);

            Intent settings = new Intent(SettingsActivity.this, SettingsActivity.class);
            PendingIntent settingsIntent = PendingIntent.getActivity(SettingsActivity.this, PENDING_SETTINGS,
                    settings, PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(SettingsActivity.this)
                    .setSmallIcon(R.drawable.ic_speedometer)
                    .setContentTitle(getString(R.string.controls_notif_title))
                    .setContentText(getString(R.string.controls_notif_desc))
                    .addAction(0, getString(R.string.show), pending)
                    .addAction(0, getString(R.string.hide), pendingClose).setDeleteIntent(pendingClose)
                    .setContentIntent(settingsIntent);
            Notification notification = builder.build();
            notificationManager.notify(NOTIFICATION_CONTROLS, notification);
        }
    });

    appSelectionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(SettingsActivity.this, AppSelectionActivity.class));
        }
    });

    appDetectionSwitch.setChecked(PrefUtils.isAutoDisplayEnabled(this));
    appDetectionContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            appDetectionSwitch.toggle();
            boolean autoDisplayEnabled = appDetectionSwitch.isChecked();
            PrefUtils.setAutoDisplay(SettingsActivity.this, autoDisplayEnabled);
            updateAppDetectionOptionStates();
        }
    });

    enableServiceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
            } catch (ActivityNotFoundException e) {
                Snackbar.make(enableServiceButton, R.string.open_settings_failed_accessibility,
                        Snackbar.LENGTH_LONG).show();
            }
        }
    });

    enableFloatingButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                //Open the current default browswer App Info page
                openSettings(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, BuildConfig.APPLICATION_ID);
            } catch (ActivityNotFoundException ignored) {
                Snackbar.make(enableFloatingButton, R.string.open_settings_failed_overlay, Snackbar.LENGTH_LONG)
                        .show();
            }
        }
    });

    enableLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ActivityCompat.requestPermissions(SettingsActivity.this,
                    new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
        }
    });

    ArrayAdapter<String> unitAdapter = new ArrayAdapter<>(this, R.layout.spinner_item_text,
            new String[] { "mph", "km/h" });
    unitAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
    unitSpinner.setAdapter(unitAdapter);
    unitSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (PrefUtils.getUseMetric(SettingsActivity.this) != (position == 1)) {
                PrefUtils.setUseMetric(SettingsActivity.this, position == 1);
                unitSpinner.setDropDownVerticalOffset(Utils.convertDpToPx(SettingsActivity.this,
                        unitSpinner.getSelectedItemPosition() * -48));

                Utils.updateFloatingServicePrefs(SettingsActivity.this);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    unitSpinner.setSelection(PrefUtils.getUseMetric(this) ? 1 : 0);
    unitSpinner
            .setDropDownVerticalOffset(Utils.convertDpToPx(this, unitSpinner.getSelectedItemPosition() * -48));

    ArrayAdapter<String> styleAdapter = new ArrayAdapter<>(this, R.layout.spinner_item_text,
            new String[] { getString(R.string.united_states), getString(R.string.international) });
    styleAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
    styleSpinner.setAdapter(styleAdapter);
    styleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position != PrefUtils.getSignStyle(SettingsActivity.this)) {
                PrefUtils.setSignStyle(SettingsActivity.this, position);
                styleSpinner.setDropDownVerticalOffset(Utils.convertDpToPx(SettingsActivity.this,
                        styleSpinner.getSelectedItemPosition() * -48));

                Utils.updateFloatingServicePrefs(SettingsActivity.this);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    styleSpinner.setSelection(PrefUtils.getSignStyle(this));
    styleSpinner
            .setDropDownVerticalOffset(Utils.convertDpToPx(this, styleSpinner.getSelectedItemPosition() * -48));

    toleranceView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ToleranceDialogFragment().show(getFragmentManager(), "dialog_tolerance");
        }
    });

    sizeView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SizeDialogFragment().show(getFragmentManager(), "dialog_size");
        }
    });

    opacityView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new OpacityDialogFragment().show(getFragmentManager(), "dialog_opacity");
        }
    });

    showSpeedometerSwitch.setChecked(PrefUtils.getShowSpeedometer(this));
    ((View) showSpeedometerSwitch.getParent()).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showSpeedometerSwitch.setChecked(!showSpeedometerSwitch.isChecked());

            PrefUtils.setShowSpeedometer(SettingsActivity.this, showSpeedometerSwitch.isChecked());

            Utils.updateFloatingServicePrefs(SettingsActivity.this);
        }
    });

    debuggingSwitch.setChecked(PrefUtils.isDebuggingEnabled(this));
    ((View) debuggingSwitch.getParent()).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            debuggingSwitch.setChecked(!debuggingSwitch.isChecked());

            PrefUtils.setDebugging(SettingsActivity.this, debuggingSwitch.isChecked());

            Utils.updateFloatingServicePrefs(SettingsActivity.this);
        }
    });

    beepSwitch.setChecked(PrefUtils.isBeepAlertEnabled(this));
    beepSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PrefUtils.setBeepAlertEnabled(SettingsActivity.this, beepSwitch.isChecked());
        }
    });
    testBeepButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.playBeep();
        }
    });

    androidAutoSwitch.setChecked(PrefUtils.isAutoIntegrationEnabled(this));
    androidAutoContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (BuildConfig.FLAVOR.equals("play")) {
                Snackbar.make(findViewById(android.R.id.content), R.string.auto_not_available,
                        Snackbar.LENGTH_LONG).show();
                return;
            }
            if (!androidAutoSwitch.isEnabled()) {
                return;
            }
            androidAutoSwitch.toggle();
            boolean checked = androidAutoSwitch.isChecked();
            if (checked) {
                new MaterialDialog.Builder(SettingsActivity.this)
                        .content(R.string.android_auto_instruction_dialog).positiveText(android.R.string.ok)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                PrefUtils.setAutoIntegrationEnabled(SettingsActivity.this, true);
                            }
                        }).show();
            } else {
                PrefUtils.setAutoIntegrationEnabled(SettingsActivity.this, checked);
            }
        }
    });

    invalidateStates();

    if (BuildConfig.VERSION_CODE > PrefUtils.getVersionCode(this) && !PrefUtils.isFirstRun(this)) {
        showChangelog();
    }

    billingProcessor = new BillingProcessor(this, getString(R.string.play_license_key),
            new BillingProcessor.IBillingHandler() {
                @Override
                public void onProductPurchased(String productId, TransactionDetails details) {
                    PrefUtils.setSupported(SettingsActivity.this, true);
                    if (Arrays.asList(PURCHASES).contains(productId))
                        billingProcessor.consumePurchase(productId);
                }

                @Override
                public void onPurchaseHistoryRestored() {

                }

                @Override
                public void onBillingError(int errorCode, Throwable error) {
                    if (errorCode != 110) {
                        Snackbar.make(findViewById(android.R.id.content),
                                "Billing error: code = " + errorCode + ", error: "
                                        + (error != null ? error.getMessage() : "?"),
                                Snackbar.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onBillingInitialized() {
                    billingProcessor.loadOwnedPurchasesFromGoogle();
                }
            });

    PrefUtils.setFirstRun(this, false);
    PrefUtils.setVersionCode(this, BuildConfig.VERSION_CODE);
}

From source file:com.google.samples.apps.iosched.gcm.command.NotificationCommand.java

private void processCommand(Context context, NotificationCommandModel command) {
    // Check format
    if (!"1.0.00".equals(command.format)) {
        LOGW(TAG, "GCM notification command has unrecognized format: " + command.format);
        return;/* w  ww.  jav a2 s  .c  o m*/
    }

    // Check app version
    if (!TextUtils.isEmpty(command.minVersion) || !TextUtils.isEmpty(command.maxVersion)) {
        LOGD(TAG, "Command has version range.");
        int minVersion = 0;
        int maxVersion = Integer.MAX_VALUE;
        try {
            if (!TextUtils.isEmpty(command.minVersion)) {
                minVersion = Integer.parseInt(command.minVersion);
            }
            if (!TextUtils.isEmpty(command.maxVersion)) {
                maxVersion = Integer.parseInt(command.maxVersion);
            }
            LOGD(TAG, "Version range: " + minVersion + " - " + maxVersion);
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            LOGD(TAG, "My version code: " + pinfo.versionCode);
            if (pinfo.versionCode < minVersion) {
                LOGD(TAG, "Skipping command because our version is too old, " + pinfo.versionCode + " < "
                        + minVersion);
                return;
            }
            if (pinfo.versionCode > maxVersion) {
                LOGD(TAG, "Skipping command because our version is too new, " + pinfo.versionCode + " > "
                        + maxVersion);
                return;
            }
        } catch (NumberFormatException ex) {
            LOGE(TAG,
                    "Version spec badly formatted: min=" + command.minVersion + ", max=" + command.maxVersion);
            return;
        } catch (Exception ex) {
            LOGE(TAG, "Unexpected problem doing version check.", ex);
            return;
        }
    }

    // Check if we are the right audience
    LOGD(TAG, "Checking audience: " + command.audience);
    if ("remote".equals(command.audience)) {
        if (SettingsUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is remote).");
        }
    } else if ("local".equals(command.audience)) {
        if (!SettingsUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is local).");
        }
    } else if ("all".equals(command.audience)) {
        LOGD(TAG, "Relevant (audience is 'all').");
    } else {
        LOGE(TAG, "Invalid audience on GCM notification command: " + command.audience);
        return;
    }

    // Check if it expired
    Date expiry = command.expiry == null ? null : TimeUtils.parseTimestamp(command.expiry);
    if (expiry == null) {
        LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry);
        return;
    } else if (expiry.getTime() < UIUtils.getCurrentTime(context)) {
        LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString());
        return;
    } else {
        LOGD(TAG, "Message is still valid (expiry is in the future: " + expiry.toString() + ")");
    }

    // decide the intent that will be fired when the user clicks the notification
    Intent intent;
    if (TextUtils.isEmpty(command.dialogText)) {
        // notification leads directly to the URL, no dialog
        if (TextUtils.isEmpty(command.url)) {
            intent = new Intent(context, MyScheduleActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(command.url));
        }
    } else {
        // use a dialog
        intent = new Intent(context, MyScheduleActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_TITLE,
                command.dialogTitle == null ? "" : command.dialogTitle);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_MESSAGE,
                command.dialogText == null ? "" : command.dialogText);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_YES,
                command.dialogYes == null ? "OK" : command.dialogYes);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_NO, command.dialogNo == null ? "" : command.dialogNo);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_URL, command.url == null ? "" : command.url);
    }

    final String title = TextUtils.isEmpty(command.title) ? context.getString(R.string.app_name)
            : command.title;
    final String message = TextUtils.isEmpty(command.message) ? "" : command.message;

    // fire the notification
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
            new NotificationCompat.Builder(context).setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_stat_notification).setTicker(command.message)
                    .setContentTitle(title).setContentText(message)
                    //.setColor(context.getResources().getColor(R.color.theme_primary))
                    // Note: setColor() is available in the support lib v21+.
                    // We commented it out because we want the source to compile 
                    // against support lib v20. If you are using support lib
                    // v21 or above on Android L, uncomment this line.
                    .setContentIntent(
                            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))
                    .setAutoCancel(true).build());
}

From source file:net.majorkernelpanic.spydroid.SpydroidActivity.java

public void onStart() {
    super.onStart();

    // Lock screen
    wl.acquire();/* w  w w.  j  av  a 2 s .  c o  m*/

    Intent notificationIntent = new Intent(this, SpydroidActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    Notification notification = builder.setContentIntent(pendingIntent).setWhen(System.currentTimeMillis())
            .setTicker(getText(R.string.notification_title)).setSmallIcon(R.drawable.icon)
            .setContentTitle(getText(R.string.notification_title))
            .setContentText(getText(R.string.notification_content)).build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);

}