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:com.example.android.wearable.wear.wearnotifications.handlers.BigTextIntentService.java

private NotificationCompat.Builder recreateBuilderWithBigTextStyle() {

    // Main steps for building a BIG_TEXT_STYLE notification (for more detailed comments on
    // building this notification, check StandaloneMainActivity.java)::
    //      0. Get your data
    //      1. Build the BIG_TEXT_STYLE
    //      2. Set up main Intent for notification
    //      3. Create additional Actions for the Notification
    //      4. Build and issue the notification

    // 0. Get your data (everything unique per Notification)
    MockDatabase.BigTextStyleReminderAppData bigTextStyleReminderAppData = MockDatabase.getBigTextStyleData();

    // 1. Build the BIG_TEXT_STYLE
    BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
            .bigText(bigTextStyleReminderAppData.getBigText())
            .setBigContentTitle(bigTextStyleReminderAppData.getBigContentTitle())
            .setSummaryText(bigTextStyleReminderAppData.getSummaryText());

    // 2. Set up main Intent for notification
    Intent mainIntent = new Intent(this, BigTextMainActivity.class);

    PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // 3. Create additional Actions (Intents) for the Notification
    // Snooze Action
    Intent snoozeIntent = new Intent(this, BigTextIntentService.class);
    snoozeIntent.setAction(BigTextIntentService.ACTION_SNOOZE);

    PendingIntent snoozePendingIntent = PendingIntent.getService(this, 0, snoozeIntent, 0);
    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_alarm_white_48dp, "Snooze", snoozePendingIntent).build();

    // Dismiss Action
    Intent dismissIntent = new Intent(this, BigTextIntentService.class);
    dismissIntent.setAction(BigTextIntentService.ACTION_DISMISS);

    PendingIntent dismissPendingIntent = PendingIntent.getService(this, 0, dismissIntent, 0);
    NotificationCompat.Action dismissAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_cancel_white_48dp, "Dismiss", dismissPendingIntent).build();

    // 4. Build and issue the notification
    NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(
            getApplicationContext());//from   ww  w  . jav  a2s . c om

    GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

    notificationCompatBuilder.setStyle(bigTextStyle)
            .setContentTitle(bigTextStyleReminderAppData.getContentTitle())
            .setContentText(bigTextStyleReminderAppData.getContentText()).setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_alarm_white_48dp))
            .setColor(getResources().getColor(R.color.colorPrimary)).setCategory(Notification.CATEGORY_REMINDER)
            .setPriority(Notification.PRIORITY_HIGH).setVisibility(Notification.VISIBILITY_PUBLIC)
            .addAction(snoozeAction).addAction(dismissAction);

    /* REPLICATE_NOTIFICATION_STYLE_CODE:
     * You can replicate Notification Style functionality on Wear 2.0 (24+) by not setting the
     * main content intent, that is, skipping the call setContentIntent(). However, you need to
     * still allow the user to open the native Wear app from the Notification itself, so you
     * add an action to launch the app.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        // Enables launching app in Wear 2.0 while keeping the old Notification Style behavior.
        NotificationCompat.Action mainAction = new NotificationCompat.Action.Builder(R.drawable.ic_launcher,
                "Open", mainPendingIntent).build();

        notificationCompatBuilder.addAction(mainAction);

    } else {
        // Wear 1.+ still functions the same, so we set the main content intent.
        notificationCompatBuilder.setContentIntent(mainPendingIntent);
    }

    return notificationCompatBuilder;
}

From source file:com.jameswolfeoliver.pigeon.Services.PigeonService.java

private Notification getNotification() {
    Intent serviceIntent = new Intent(PigeonApplication.getAppContext(), PigeonService.class);
    serviceIntent.putExtra(PigeonService.COMMAND_KEY, PigeonService.Commands.COMMAND_STOP);
    PendingIntent stopIntent = PendingIntent.getService(this, 0, serviceIntent, 0);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ConnectionActivity.class),
            0);/*from   w  w  w. j ava 2s . co  m*/
    return new NotificationCompat.Builder(this).setSmallIcon(R.drawable.app_icon)
            .setWhen(System.currentTimeMillis())
            .addAction(R.drawable.ic_phonelink_off_light, getString(R.string.disconnect), stopIntent)
            .setOngoing(true).setContentTitle(getText(R.string.app_name))
            .setContentText(getText(R.string.server_running))
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(String.format(getString(R.string.connected_message), pigeonServer.getServerUri())))
            .setContentIntent(contentIntent).build();
}

From source file:com.group13.androidsdk.mycards.NotificationService.java

private void rescheduleNotifications() {

    List<NotificationRule> rules = new ArrayList<>();
    Collections.addAll(rules, MyCardsDBManager.getInstance(this).getAllNotificationRules());
    rules.addAll(getCalendarAsNotificationRules());

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    long lastNotifMillis = prefs.getLong("lastNotifElapsedRealtime", -2 * FIFTEEN_MINUTES);
    SharedPreferences.Editor prefEditor = prefs.edit();

    MyCardsDBManager dbm = MyCardsDBManager.getInstance(this);
    if (!(Math.abs(lastNotifMillis - SystemClock.elapsedRealtime()) < FIFTEEN_MINUTES || dbm.getDoNotDisturb()
            || dateMatchesAnyRule(new Date(), rules)
            || dbm.getCardsForReviewBefore(new Date(), null).length == 0)) {
        lastNotifMillis = SystemClock.elapsedRealtime();
        prefEditor.putLong("lastNotifElapsedRealtime", lastNotifMillis);

        sendNotification();/* w  ww  . j  av a2  s  . c om*/
    }

    Intent intent = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + FIFTEEN_MINUTES, pi);

    prefEditor.putLong("lastRunElapsedRealtime", SystemClock.elapsedRealtime());
    prefEditor.apply();
}

From source file:com.tingtingapps.securesms.service.KeyCachingService.java

@Override
public void onCreate() {
    Log.w("KeyCachingService", "onCreate()");
    super.onCreate();
    this.pending = PendingIntent.getService(this, 0,
            new Intent(PASSPHRASE_EXPIRED_EVENT, null, this, KeyCachingService.class), 0);

    if (TextSecurePreferences.isPasswordDisabled(this)) {
        try {//from   w  w  w.j  a  v a2  s . c  om
            MasterSecret masterSecret = MasterSecretUtil.getMasterSecret(this,
                    MasterSecretUtil.UNENCRYPTED_PASSPHRASE);
            setMasterSecret(masterSecret);
        } catch (InvalidPassphraseException e) {
            Log.w("KeyCachingService", e);
        }
    }
}

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

static synchronized void showHighPriorityNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying high priority notification for alarm instance: " + instance.mId);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setShowWhen(false)
            .setContentTitle(//from www. jav  a2 s .  c  om
                    context.getString(com.androidinspain.deskclock.R.string.alarm_alert_predismiss_title))
            .setContentText(AlarmUtils.getAlarmText(context, instance, true /* includeLabel */))
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm).setAutoCancel(false)
            .setSortKey(createSortKey(instance)).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);

    if (Utils.isNOrLater()) {
        builder.setGroup(UPCOMING_GROUP_KEY);
    }

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.PREDISMISSED_STATE);
    final int id = instance.hashCode();
    builder.addAction(com.androidinspain.deskclock.R.drawable.ic_alarm_off_24dp,
            context.getString(com.androidinspain.deskclock.R.string.alarm_alert_dismiss_text),
            PendingIntent.getService(context, id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

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

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    final Notification notification = builder.build();
    nm.notify(id, notification);
    updateUpcomingAlarmGroupNotification(context, -1, notification);
}

From source file:com.adam.aslfms.service.ScrobblingService.java

@Override
public int onStartCommand(Intent i, int flags, int startId) {
    handleCommand(i, startId);/*from www. j a  v  a  2 s . c o m*/
    if (settings.isOnGoingEnabled(Util.checkPower(mCtx))) {
        if (mCurrentTrack != null) {
            String ar = mCurrentTrack.getArtist();
            String tr = mCurrentTrack.getTrack();
            String api = mCurrentTrack.getMusicAPI().readAPIname();

            // Heart intent
            Intent heartIntent = new Intent(mCtx, ScrobblingService.class);
            heartIntent.setAction(ScrobblingService.ACTION_HEART);
            PendingIntent heartPendingIntent = PendingIntent.getService(mCtx, 0, heartIntent, 0);
            NotificationCompat.Action heartAction = new NotificationCompat.Action.Builder(
                    R.mipmap.ic_status_wail_love_track, "", heartPendingIntent).build();

            Intent targetIntent = new Intent(mCtx, SettingsActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(mCtx, 0, targetIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(mCtx).setContentTitle(tr)
                    .setSmallIcon(R.mipmap.ic_notify).setContentText(ar + " :" + api)
                    .setPriority(NotificationCompat.PRIORITY_MIN).addAction(heartAction)
                    .setContentIntent(contentIntent);

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {
                builder.setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher));
            }

            this.startForeground(14619, builder.build());

            if (!settings.isNotifyEnabled(Util.checkPower(mCtx))) {
                Intent iNoti = new Intent(mCtx, ForegroundHide.class);
                startService(iNoti);
            }
        }
    } else {
        this.stopForeground(true); // TODO: test if this conflicts/stops scrobbles
    }
    return Service.START_STICKY;
}

From source file:com.github.sryze.wirebug.DebugStatusService.java

private void updateStatus() {
    Log.i(TAG, "Performing a status update...");

    boolean isEnabled = DebugManager.isTcpDebuggingEnabled();
    if (isEnabled != isCurrentlyEnabled) {
        Log.i(TAG, String.format("Status has changed to %s", isEnabled ? "enabled" : "disabled"));
        sendStatusChangedBroadcast(isEnabled);
    } else {/*from   www.j a v a  2 s. co  m*/
        Log.i(TAG, "Status is unchanged");
    }

    if (keyguardManager.inKeyguardRestrictedInputMode() && preferences.getBoolean("disable_on_lock", false)) {
        Log.i(TAG, "Disabling debugging because disable_on_lock is true");
        DebugManager.setTcpDebuggingEnabled(false);
    }

    if (isEnabled) {
        boolean isConnectedToWifi = NetworkUtils.isConnectedToWifi(connectivityManager);
        Log.d(TAG, String.format("Connected to Wi-Fi: %s", isConnectedToWifi ? "yes" : "no"));

        Intent contentIntent = new Intent(this, MainActivity.class);
        contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        Intent stopIntent = new Intent(this, DebugStatusService.class);
        stopIntent.setAction(ACTION_STOP);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder.setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.notification_title))
                .setContentIntent(
                        PendingIntent.getActivity(this, 0, contentIntent, PendingIntent.FLAG_CANCEL_CURRENT))
                .addAction(R.drawable.ic_stop, getString(R.string.notification_action_stop),
                        PendingIntent.getService(this, 0, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT));

        if (isConnectedToWifi) {
            notificationBuilder.setContentText(String.format(getString(R.string.notification_text),
                    NetworkUtils.getWifiIpAddressString(wifiManager),
                    NetworkUtils.getWifiNetworkName(wifiManager)));
        } else {
            notificationBuilder.setContentText(getString(R.string.notification_text_not_connected));
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            notificationBuilder.setCategory(Notification.CATEGORY_STATUS)
                    .setVisibility(Notification.VISIBILITY_PUBLIC);
        }

        Notification notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notificationManager.notify(STATUS_NOTIFICATION_ID, notification);
    } else {
        Log.d(TAG, "Canceling the notification");
        notificationManager.cancel(STATUS_NOTIFICATION_ID);
    }

    if (isEnabled && preferences.getBoolean("stay_awake", false)) {
        if (wakeLock != null && !wakeLock.isHeld()) {
            Log.i(TAG, "Acquiring a wake lock because stay_awake is true");
            wakeLock.acquire();
        }
    } else {
        if (wakeLock != null && wakeLock.isHeld()) {
            Log.i(TAG, "Releasing the wake lock");
            wakeLock.release();
        }
    }

    isCurrentlyEnabled = isEnabled;
}

From source file:com.remdo.app.MainActivity.java

/**
 * This method checks services state, and configure MainActivity layout to be displayed accordingly.
 *///from  www .  j  a  v  a 2  s  .  com
private void checkServices() {
    TextView TVGeo = (TextView) findViewById(R.id.tv_geo_footer);
    TextView TVAlerts = (TextView) findViewById(R.id.tv_alerts_footer);

    Intent myIntent = new Intent(this, GeopositioningService.class);
    pendingGeoIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_NO_CREATE);
    myIntent = new Intent(this, NotificationService.class);
    pendingAlertsIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_NO_CREATE);

    //Comprobamos si el servicio GEO esta iniciado

    if (!isGEORunning()) {
        TVGeo.setTextColor(this.getResources().getColor(R.color.Red));
        TVGeo.setText(R.string.geo_off);
        GeoEnabled = false;
    } else {
        TVGeo.setTextColor(this.getResources().getColor(R.color.Black));
        TVGeo.setText(R.string.geo_on);
        GeoEnabled = true;
    }

    //Comprobamos si el servicio Alerts esta  iniciado
    if (!isALERTSRunning()) {
        TVAlerts.setTextColor(this.getResources().getColor(R.color.Red));
        TVAlerts.setText(R.string.alerts_off);
        AlertsEnabled = false;
    } else {
        TVAlerts.setTextColor(this.getResources().getColor(R.color.Black));
        TVAlerts.setText(R.string.alerts_on);
        AlertsEnabled = true;
    }

}

From source file:cc.softwarefactory.lokki.android.androidServices.LocationService.java

private void setTemporalTimer() {
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, LocationService.class);
    alarmIntent.putExtra(ALARM_TIMER, 1);
    PendingIntent alarmCallback = PendingIntent.getService(this, 0, alarmIntent, 0);
    alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + INTERVAL_1_MIN,
            alarmCallback);//from  ww  w. java2  s  .c  om
    Log.d(TAG, "Time created.");
}

From source file:com.orpheusdroid.screenrecorder.RecorderService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //return super.onStartCommand(intent, flags, startId);
    //Find the action to perform from intent
    switch (intent.getAction()) {
    case Const.SCREEN_RECORDING_START:
        /* Wish MediaRecorder had a method isRecording() or similar. But, we are forced to
         * manage the state ourself. Let's hope the request is honored.
          * Request: https://code.google.com/p/android/issues/detail?id=800 */
        if (!isRecording) {
            //Get values from Default SharedPreferences
            getValues();//from  ww  w  . j  a v  a2  s  .c o  m
            Intent data = intent.getParcelableExtra(Const.RECORDER_INTENT_DATA);
            int result = intent.getIntExtra(Const.RECORDER_INTENT_RESULT, Activity.RESULT_OK);

            //Initialize MediaRecorder class and initialize it with preferred configuration
            mMediaRecorder = new MediaRecorder();
            initRecorder();

            //Set Callback for MediaProjection
            mMediaProjectionCallback = new MediaProjectionCallback();
            MediaProjectionManager mProjectionManager = (MediaProjectionManager) getSystemService(
                    Context.MEDIA_PROJECTION_SERVICE);

            //Initialize MediaProjection using data received from Intent
            mMediaProjection = mProjectionManager.getMediaProjection(result, data);
            mMediaProjection.registerCallback(mMediaProjectionCallback, null);

            /* Create a new virtual display with the actual default display
             * and pass it on to MediaRecorder to start recording */
            mVirtualDisplay = createVirtualDisplay();
            try {
                mMediaRecorder.start();
                isRecording = true;
                Toast.makeText(this, R.string.screen_recording_started_toast, Toast.LENGTH_SHORT).show();
            } catch (IllegalStateException e) {
                Log.d(Const.TAG,
                        "Mediarecorder reached Illegal state exception. Did you start the recording twice?");
                Toast.makeText(this, R.string.recording_failed_toast, Toast.LENGTH_SHORT).show();
                isRecording = false;
            }

            /* Add Pause action to Notification to pause screen recording if the user's android version
             * is >= Nougat(API 24) since pause() isnt available previous to API24 else build
             * Notification with only default stop() action */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //startTime is to calculate elapsed recording time to update notification during pause/resume
                startTime = System.currentTimeMillis();
                Intent recordPauseIntent = new Intent(this, RecorderService.class);
                recordPauseIntent.setAction(Const.SCREEN_RECORDING_PAUSE);
                PendingIntent precordPauseIntent = PendingIntent.getService(this, 0, recordPauseIntent, 0);
                NotificationCompat.Action action = new NotificationCompat.Action(
                        android.R.drawable.ic_media_pause,
                        getString(R.string.screen_recording_notification_action_pause), precordPauseIntent);

                //Start Notification as foreground
                startNotificationForeGround(createNotification(action).build(),
                        Const.SCREEN_RECORDER_NOTIFICATION_ID);
            } else
                startNotificationForeGround(createNotification(null).build(),
                        Const.SCREEN_RECORDER_NOTIFICATION_ID);
        } else {
            Toast.makeText(this, R.string.screenrecording_already_active_toast, Toast.LENGTH_SHORT).show();
        }
        break;
    case Const.SCREEN_RECORDING_PAUSE:
        pauseScreenRecording();
        break;
    case Const.SCREEN_RECORDING_RESUME:
        resumeScreenRecording();
        break;
    case Const.SCREEN_RECORDING_STOP:
        stopScreenSharing();
        //The service is started as foreground service and hence has to be stopped
        stopForeground(true);
        break;
    }
    return START_STICKY;
}