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:au.com.smarttrace.beacons.BluetoothService.java

private void connect() {
    btScanner = btAdapter.getBluetoothLeScanner();
    if (btScanner != null && btAdapter.isEnabled()) {

        Log.d(TAG, "START SCANNING!");
        btScanner.startScan(btFilters, btSettings, scanCallback);
        scanning = true;/*from  www .  j  a v  a2s .co m*/
        sendChange(true);

        //XXX: workaround to avoid bluetooth scan halt
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(BluetoothService.ACTION_RESCAN, null, this, BluetoothService.class);
        alarm.setExact(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 15000l,
                PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));

        //         future = executor.schedule(this, DELAY_REPEAT_SCAN, TimeUnit.SECONDS);
    }
}

From source file:info.papdt.blacklight.support.Utility.java

public static void startServiceAlarm(Context context, Class<?> service, long interval) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, service);
    PendingIntent p = PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, p);
}

From source file:com.klinker.android.twitter.services.TalonPullNotificationService.java

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

    if (TalonPullNotificationService.isRunning) {
        stopSelf();//from  ww  w  . j a  va  2  s  .  c  o m
        return;
    }

    TalonPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    pullUnread = sharedPreferences.getInt("pull_unread", 0);

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

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    Intent popup = new Intent(this, RedirectToPopup.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    popup.putExtra("from_notification", true);
    PendingIntent popupPending = PendingIntent.getActivity(this, 0, popup, 0);

    Intent compose = new Intent(this, WidgetCompose.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent composePending = PendingIntent.getActivity(this, 0, compose, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.talon_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
        mBuilder.addAction(R.drawable.ic_popup, getResources().getString(R.string.popup), popupPending);
        mBuilder.addAction(R.drawable.ic_send_dark, getResources().getString(R.string.tweet), composePending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;
                int rep = 0;

                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    ids = new ArrayList<Long>();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }

                    rep++;
                } while ((currCursor = idObject.getNextCursor()) != 0 && rep < 3);

                ids.add(settings.myId);

                idsLoaded = true;

                startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.klinker.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TalonPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TalonPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}

From source file:com.ayuget.redface.job.PrivateMessagesService.java

@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/*from   ww w  .  j a v a 2s .co m*/
protected void onHandleIntent(Intent intent) {
    Log.d(LOG_TAG, "Handling intent");

    if (!settings.arePrivateMessagesNoticationsEnabled()) {
        return;
    }

    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(getApplicationContext());

    for (User redfaceUser : userManager.getRealUsers()) {
        subscriptions.add(mdService.getNewPrivateMessages(redfaceUser)
                .subscribe(new EndlessObserver<List<PrivateMessage>>() {
                    @Override
                    public void onNext(List<PrivateMessage> privateMessages) {
                        for (PrivateMessage privateMessage : privateMessages) {
                            // Prepare intent to deal with clicks
                            Intent resultIntent = new Intent(PrivateMessagesService.this,
                                    PrivateMessagesActivity.class);
                            resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            resultIntent.putExtra(UIConstants.ARG_SELECTED_PM, privateMessage);
                            PendingIntent resultPendingIntent = PendingIntent.getActivity(
                                    getApplicationContext(), 0, resultIntent,
                                    PendingIntent.FLAG_UPDATE_CURRENT);

                            NotificationCompat.Builder builder = new NotificationCompat.Builder(
                                    getApplicationContext()).setSmallIcon(R.drawable.ic_action_emo_wonder)
                                            .setColor(getResources().getColor(R.color.theme_primary))
                                            .setContentTitle(privateMessage.getRecipient())
                                            .setContentText(privateMessage.getSubject())
                                            .setContentIntent(resultPendingIntent).setAutoCancel(true);

                            builder.setVibrate(VIBRATION_PATTERN);

                            notificationManager.notify((int) privateMessage.getId(), builder.build());
                        }
                    }
                }));
    }

    // Setup next alarm
    long wakeUpTime = System.currentTimeMillis()
            + settings.getPrivateMessagesPollingFrequency() * DateUtils.MINUTE_IN_MILLIS;
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, PrivateMessagesService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Log.d(LOG_TAG, "Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }

}

From source file:de.grundid.plusrad.recording.RecordingService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "recording service create");
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    dbAdapter = new DbAdapter(getApplicationContext());
    Intent intent = new Intent(this, ActivityRecognitionIntentService.class);
    pendingIntentForActivityRecorgnition = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    apiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API).addApi(LocationServices.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
    apiClient.connect();/*from  w  w w. j a  v a  2 s.co m*/
    broadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
    broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("PRAD", "activity update: " + intent.getStringExtra("activityName"));
            activityType = intent.getIntExtra("activityType", DetectedActivity.UNKNOWN);
        }
    };
}

From source file:com.kosratdahmad.location.MainActivity.java

private PendingIntent getActivityDetectionPendingIntent() {
    Intent intent = new Intent(this, DetectedActivitiesIntentService.class);

    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // requestActivityUpdates() and removeActivityUpdates().
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.jerrellmardis.amphitheatre.util.Utils.java

public static void scheduleRecommendations(Context context) {
    Log.d("amp:Utils",
            "Checking if alarm is already set: " + isAlarmAlreadySet(context, RecommendationsService.class));
    //And now//w ww  . ja va2 s . c  om
    Log.d("amp:Utils", "Start rechecking the recommendations");
    Intent intent = new Intent(context, RecommendationsService.class);
    intent.putExtra("ALARM", true);
    /*context.startService(intent);*/
    if (isAlarmAlreadySet(context, RecommendationsService.class))
        return;

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    //Intent intent = ...
    PendingIntent alarmIntent = PendingIntent.getService(context, LIBRARY_UPDATE_REQUEST_CODE, intent, 0);

    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 5000,
            AlarmManager.INTERVAL_HALF_HOUR, //Every half hour seems sufficient
            alarmIntent);

}

From source file:com.android.deskclock.alarms.AlarmNotifications.java

public static void showSnoozeNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying snoozed notification for alarm instance: " + instance.mId);

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(instance.getLabelOrDefault(context))
            .setContentText(context.getString(R.string.alarm_alert_snooze_until,
                    AlarmUtils.getFormattedTime(context, instance.getAlarmTime())))
            .setSmallIcon(R.drawable.stat_notify_alarm).setAutoCancel(false).setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MAX).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setLocalOnly(true);

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    notification.addAction(R.drawable.ic_alarm_off_24dp, context.getString(R.string.alarm_alert_dismiss_text),
            PendingIntent.getService(context, instance.hashCode(), dismissIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content action if instance is owned by alarm
    Intent viewAlarmIntent = createViewAlarmIntent(context, instance);
    notification.setContentIntent(PendingIntent.getActivity(context, instance.hashCode(), viewAlarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(instance.hashCode(), notification.build());
}

From source file:com.crearo.gpslogger.GpsLoggingService.java

private void requestActivityRecognitionUpdates() {
    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(getApplicationContext())
            .addApi(ActivityRecognition.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {

                @Override//from  ww  w  .  ja v  a 2 s.  c  om
                public void onConnectionSuspended(int arg) {
                }

                @Override
                public void onConnected(Bundle arg0) {
                    try {
                        LOG.debug("Requesting activity recognition updates");
                        Intent intent = new Intent(getApplicationContext(), GpsLoggingService.class);
                        activityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 0,
                                intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(googleApiClient,
                                preferenceHelper.getMinimumLoggingInterval() * 1000,
                                activityRecognitionPendingIntent);
                    } catch (Throwable t) {
                        LOG.warn(SessionLogcatAppender.MARKER_INTERNAL,
                                "Can't connect to activity recognition service", t);
                    }

                }

            }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult arg0) {

                }
            });

    googleApiClient = builder.build();
    googleApiClient.connect();
}

From source file:com.example.mego.adas.utils.NotificationUtils.java

/**
 * Helper method for the action cancel//from  w  w w.j av a 2  s.  c om
 */
private static NotificationCompat.Action ignoreAccident(Context context) {
    Intent ignoreAccidentIntent = new Intent(context, CarAdviceAssistantIntentService.class);

    ignoreAccidentIntent.setAction(AdasSyncTasks.ACTION_DISMISS_NOTIFICATION);

    PendingIntent ignoreAccidentPendingIntent = PendingIntent.getService(context,
            ADAS_ACCIDENT_PENDING_INTENT_ID, ignoreAccidentIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Action ignoreAccidentAction = new NotificationCompat.Action(
            R.drawable.ic_cancel_black_24px, context.getString(R.string.cancel), ignoreAccidentPendingIntent);

    return ignoreAccidentAction;
}