Example usage for android.app PendingIntent getService

List of usage examples for android.app PendingIntent getService

Introduction

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

Prototype

public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent,
        @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will start a service, like calling Context#startService Context.startService() .

Usage

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Make notification and post it to the NotificationManager
 * //w w w  .jav  a 2 s.  co m
 * @param tickerIcon
 *            Icon shown in notification bar
 * @param contentIcon
 *            Icon shown in notification
 * @param tickerText
 *            Text shown in notification bar
 * @param contentTitle
 *            Title shown in notification
 * @param contentText
 *            Description shown in notification
 * @param contentTime
 *            Time shown in notification
 * @param when2
 */
private void makeNotification(int tickerIcon, int contentIcon, CharSequence tickerText,
        CharSequence contentTitle, CharSequence contentText, CharSequence contentTime, long when2,
        Float temperature) {
    final long when = System.currentTimeMillis();
    // Make notification
    Notification notification = null;

    final Intent notificationIntent = new Intent(WeatherNotificationService.this,
            WeatherNotificationService.class);
    final PendingIntent contentIntent = PendingIntent.getService(WeatherNotificationService.this, 0,
            notificationIntent, 0);

    // Check if Notification.Builder exists (11+)
    if (Build.VERSION.SDK_INT >= 11) {
        // Honeycomb ++
        NotificationBuilder builder = new NotificationBuilder(this);
        builder.setAutoCancel(false);
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setTicker(tickerText);
        builder.setWhen(when2);
        builder.setSmallIcon(tickerIcon);
        builder.setOngoing(true);
        builder.setContentIntent(contentIntent);
        if (temperature != null)
            builder.makeContentView(contentTitle, contentText, when2, temperature, tickerIcon);
        notification = builder.getNotification();
    } else {
        // Gingerbread --
        notification = new Notification(tickerIcon, tickerText, when);
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.weathernotification);
        contentView.setImageViewResource(R.id.icon, contentIcon);
        contentView.setTextViewText(R.id.title, contentTitle);
        contentView.setTextViewText(R.id.title, contentTitle);
        contentView.setTextViewText(R.id.text, contentText);
        contentView.setTextViewText(R.id.time, contentTime);
        notification.contentView = contentView;
    }
    notification.contentIntent = contentIntent;

    // Post notification
    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, notification);
}

From source file:markson.visuals.sitapp.settingActivity.java

public void notifications() {
    // get a Calendar object with current time

    Intent intent = new Intent(getApplicationContext(), ClassesService.class);
    //intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    try {/* w  ww .  j  a  v a 2s  .c  o m*/
        pi.send();
    } catch (PendingIntent.CanceledException e) {
        // the stack trace isn't very helpful here.  Just log the exception message.  
        System.out.println("Sending Notification failed ");
    }
    /*Calendar calendar = Calendar.getInstance();
            
      calendar.set(Calendar.HOUR_OF_DAY, 07);
      calendar.set(Calendar.MINUTE, 00);
      calendar.set(Calendar.SECOND, 00);
    // add 5 minutes to the calendar object
    //cal.add(Calendar.SECOND, 10);
    Log.e("Testing", "Calender Set time:"+calendar.getTime());
            
    //Log.e("Testing", "Intent created");
    //intent.putExtra("alarm_message", "O'Doyle Rules!");
    // In reality, you would want to have a static variable for the request code instead of 192837
            
    AlarmManager alarm_manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
      alarm_manager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),24*60*60*1000, pi);*/
}

From source file:com.androidinspain.deskclock.Utils.java

/**
 * Update and return the PendingIntent corresponding to the given {@code intent}.
 *
 * @param context the Context in which the PendingIntent should start the service
 * @param intent  an Intent describing the service to be started
 * @return a PendingIntent that will start a service
 *//*from  ww  w  . ja v  a  2s.  c  om*/
public static PendingIntent pendingServiceIntent(Context context, Intent intent) {
    return PendingIntent.getService(context, 0, intent, FLAG_UPDATE_CURRENT);
}

From source file:br.com.devfest.norte.wear.HomeListenerService.java

/**
 * Builds notification for wear based on the data in the Data Item that is passed in.
 *///from   w  w  w .ja v a 2s .c om
private void setupNotification(DataItem dataItem) {
    LOGD(TAG, "setupNotification(): DataItem=" + dataItem.getUri());
    PutDataMapRequest putDataMapRequest = PutDataMapRequest
            .createFromDataMapItem(DataMapItem.fromDataItem(dataItem));
    final DataMap dataMap = putDataMapRequest.getDataMap();
    String sessionId = dataMap.getString(KEY_SESSION_ID);
    String sessionRoom = dataMap.getString(KEY_SESSION_ROOM);
    String sessionName = dataMap.getString(KEY_SESSION_NAME);
    String speakers = dataMap.getString(KEY_SPEAKER_NAME);

    int notificationId = (int) new Date().getTime();
    Intent intent = new Intent(ACTION_DISMISS);
    intent.putExtra(KEY_SESSION_ID, dataMap.getString(KEY_SESSION_ID));

    // need to be notified if user dismisses teh notification so we can dismiss the
    // corresponding notification on teh paired handset.
    PendingIntent deleteIntent = PendingIntent.getService(this, notificationId, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    PendingIntent showCardIntent = showCardIntent(sessionId, sessionRoom, sessionName, speakers,
            notificationId);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(getString(R.string.rate_this_session))
            .setDeleteIntent(deleteIntent).setContentText(sessionName)
            .extend(new NotificationCompat.WearableExtender().setDisplayIntent(showCardIntent));

    NotificationManagerCompat.from(this).notify(sessionId, NOTIFICATION_ID, builder.build());
}

From source file:com.ncode.android.apps.schedo.iowear.HomeListenerService.java

/**
 * Builds notification for wear based on the data in the Data Item that is passed in.
 *//*from   w  w  w .  j  a  v  a2 s . co m*/
private void setupNotification(DataItem dataItem) {
    Utils.LOGD(TAG, "setupNotification(): DataItem=" + dataItem.getUri());
    PutDataMapRequest putDataMapRequest = PutDataMapRequest
            .createFromDataMapItem(DataMapItem.fromDataItem(dataItem));
    final DataMap dataMap = putDataMapRequest.getDataMap();
    String sessionId = dataMap.getString(KEY_SESSION_ID);
    String sessionRoom = dataMap.getString(KEY_SESSION_ROOM);
    String sessionName = dataMap.getString(KEY_SESSION_NAME);
    String speakers = dataMap.getString(KEY_SPEAKER_NAME);

    int notificationId = (int) new Date().getTime();
    Intent intent = new Intent(ACTION_DISMISS);
    intent.putExtra(KEY_SESSION_ID, dataMap.getString(KEY_SESSION_ID));

    // need to be notified if user dismisses teh notification so we can dismiss the
    // corresponding notification on teh paired handset.
    PendingIntent deleteIntent = PendingIntent.getService(this, notificationId, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    PendingIntent showCardIntent = showCardIntent(sessionId, sessionRoom, sessionName, speakers,
            notificationId);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(getString(R.string.rate_this_session))
            .setDeleteIntent(deleteIntent).setContentText(sessionName)
            .extend(new NotificationCompat.WearableExtender().setDisplayIntent(showCardIntent));

    NotificationManagerCompat.from(this).notify(sessionId, NOTIFICATION_ID, builder.build());
}

From source file:com.hodor.company.areminder.ui.MainActivity.java

public void startAlarm() {
    long time = getTime();
    NotificationManagerCompat notificationManager = getNotificationManager();
    notificationManager.cancel(NOTIFICATION_ID);

    Intent removeIntent = new Intent(ACTION_REMOVE_TIMER, null, this, TimerService.class);
    PendingIntent pendingRemoveIntent = PendingIntent.getService(this, 0, removeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent showIntent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            .putExtra(MainActivity.ACTION_REMOVE_TIMER, 1);
    PendingIntent pendingShowIntent = PendingIntent.getActivity(this, 0, showIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = NotificationCenter.getNotificationCenter(this).buildAlarmNotification(
            category.ordinal(), (int) (time * 1000), pendingRemoveIntent, pendingShowIntent);
    notificationManager.notify(NOTIFICATION_ID, notification);
    registerAlarmManager(time * 1000);// w  ww  .j  a  v  a2 s . c o m
}

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

@SuppressWarnings("ConstantConditions")
@Override/*from  w  w w.  j  av a  2 s. c  om*/
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:net.networksaremadeofstring.rhybudd.ZenossPoller.java

private void PollerCheck() {
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent Poller = new Intent(this, ZenossPoller.class);

    if (settings.getBoolean("AllowBackgroundService", true)) {
        //Log.i("PollerCheck","Background scanning enabled!");
        Notifications.SendStickyNotification(this);

        Poller.putExtra("events", true);
        PendingIntent Monitoring = PendingIntent.getService(this, 0, Poller, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.FLAG_UPDATE_CURRENT
        am.cancel(Monitoring);//from ww  w.  j a va2 s.  co m
        try {
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, (long) 0,
                    Long.parseLong(settings.getString("BackgroundServiceDelay", "60")) * 1000, Monitoring);
        } catch (Exception e) {
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, (long) 0, 60000, Monitoring);
            BugSenseHandler.sendExceptionMessage("ZenossPoller", "PollerCheck", e);
        }
    } else {
        //Log.i("PollerCheck","Background scanning disabled!");
        Poller.putExtra("events", true);
        PendingIntent Monitoring = PendingIntent.getService(this, 0, Poller, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.FLAG_UPDATE_CURRENT
        am.cancel(Monitoring);
        mNM.cancel(Notifications.NOTIFICATION_POLLED_STICKY);
    }

    /*if(settings.getBoolean("refreshCache", true))
    {
       //Log.i("PollerCheck","Background cache refresh enabled!");
               
       Poller.putExtra("refreshCache", true);
       PendingIntent CacheRefresh = PendingIntent.getService(this, 1, Poller, PendingIntent.FLAG_UPDATE_CURRENT);
       am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 10000, AlarmManager.INTERVAL_HOUR, CacheRefresh);
    }
    else
    {
       //Log.i("PollerCheck","Background cache refresh disabled!");
       Poller.putExtra("refreshCache", true);
       PendingIntent CacheRefresh = PendingIntent.getService(this, 1, Poller, PendingIntent.FLAG_UPDATE_CURRENT);
       am.cancel(CacheRefresh);
    }*/

    //We use a SyncAdapter now like good citizens
    try {
        if (settings.getBoolean("refreshCache", true)) {
            Poller.putExtra("refreshCache", true);
            PendingIntent CacheRefresh = PendingIntent.getService(this, 1, Poller,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            am.cancel(CacheRefresh);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("refreshCache", false);
            editor.commit();
        }
    } catch (Exception e) {
        e.printStackTrace();
        BugSenseHandler.sendExceptionMessage("ZenossPoller", "cancel refresh cache poller", e);
    }
}

From source file:edu.mit.media.funf.configured.ConfiguredPipeline.java

protected PendingIntent getCallback() {
    // TODO: Maybe do a callback per probe, so they can be cancelled individually
    return PendingIntent.getService(this, 0, new Intent(this, getClass()), PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:de.quist.app.errorreporter.ExceptionReportService.java

private void sendReport(Intent intent) throws UnsupportedEncodingException, NameNotFoundException {
    Log.v(TAG, "Got request to report error: " + intent.toString());
    Uri server = getTargetUrl();/*from   ww  w.java  2 s.c  o m*/

    boolean isManualReport = intent.getBooleanExtra(EXTRA_MANUAL_REPORT, false);
    boolean isReportOnFroyo = isReportOnFroyo();
    boolean isFroyoOrAbove = isFroyoOrAbove();
    if (isFroyoOrAbove && !isManualReport && !isReportOnFroyo) {
        // We don't send automatic reports on froyo or above
        Log.d(TAG, "Don't send automatic report on froyo");
        return;
    }

    Set<String> fieldsToSend = getFieldsToSend();

    String stacktrace = intent.getStringExtra(EXTRA_STACK_TRACE);
    String exception = intent.getStringExtra(EXTRA_EXCEPTION_CLASS);
    String message = intent.getStringExtra(EXTRA_MESSAGE);
    long availableMemory = intent.getLongExtra(EXTRA_AVAILABLE_MEMORY, -1l);
    long totalMemory = intent.getLongExtra(EXTRA_TOTAL_MEMORY, -1l);
    String dateTime = intent.getStringExtra(EXTRA_EXCEPTION_TIME);
    String threadName = intent.getStringExtra(EXTRA_THREAD_NAME);
    String extraMessage = intent.getStringExtra(EXTRA_EXTRA_MESSAGE);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    addNameValuePair(params, fieldsToSend, "exStackTrace", stacktrace);
    addNameValuePair(params, fieldsToSend, "exClass", exception);
    addNameValuePair(params, fieldsToSend, "exDateTime", dateTime);
    addNameValuePair(params, fieldsToSend, "exMessage", message);
    addNameValuePair(params, fieldsToSend, "exThreadName", threadName);
    if (extraMessage != null)
        addNameValuePair(params, fieldsToSend, "extraMessage", extraMessage);
    if (availableMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devAvailableMemory", availableMemory + "");
    if (totalMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devTotalMemory", totalMemory + "");

    PackageManager pm = getPackageManager();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
        addNameValuePair(params, fieldsToSend, "appVersionCode", packageInfo.versionCode + "");
        addNameValuePair(params, fieldsToSend, "appVersionName", packageInfo.versionName);
        addNameValuePair(params, fieldsToSend, "appPackageName", packageInfo.packageName);
    } catch (NameNotFoundException e) {
    }
    addNameValuePair(params, fieldsToSend, "devModel", android.os.Build.MODEL);
    addNameValuePair(params, fieldsToSend, "devSdk", android.os.Build.VERSION.SDK);
    addNameValuePair(params, fieldsToSend, "devReleaseVersion", android.os.Build.VERSION.RELEASE);

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(server.toString());
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    Log.d(TAG, "Created post request");

    try {
        httpClient.execute(post);
        Log.v(TAG, "Reported error: " + intent.toString());
    } catch (ClientProtocolException e) {
        // Ignore this kind of error
        Log.e(TAG, "Error while sending an error report", e);
    } catch (SSLException e) {
        Log.e(TAG, "Error while sending an error report", e);
    } catch (IOException e) {
        if (e instanceof SocketException && e.getMessage().contains("Permission denied")) {
            Log.e(TAG, "You don't have internet permission", e);
        } else {
            int maximumRetryCount = getMaximumRetryCount();
            int maximumExponent = getMaximumBackoffExponent();
            // Retry at a later point in time
            AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            int exponent = intent.getIntExtra(EXTRA_CURRENT_RETRY_COUNT, 0);
            intent.putExtra(EXTRA_CURRENT_RETRY_COUNT, exponent + 1);
            PendingIntent operation = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (exponent >= maximumRetryCount) {
                // Discard error
                Log.w(TAG, "Error report reached the maximum retry count and will be discarded.\nStacktrace:\n"
                        + stacktrace);
                return;
            }
            if (exponent > maximumExponent) {
                exponent = maximumExponent;
            }
            long backoff = (1 << exponent) * 1000; // backoff in ms
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + backoff, operation);
        }
    }
}