Example usage for android.app PendingIntent getActivity

List of usage examples for android.app PendingIntent getActivity

Introduction

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

Prototype

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

Source Link

Document

Retrieve a PendingIntent that will start a new activity, like calling Context#startActivity(Intent) Context.startActivity(Intent) .

Usage

From source file:me.gpelaez.cordova.plugins.ibeacon.GPIBeacon.java

/**
 * + * Issues a notification to inform the user that server has sent a
 * message. +//from w w  w. jav a 2  s. c  o m
 * @throws JSONException 
 */
@SuppressLint("InlinedApi")
private static void createNotification(Context context, JSONObject json) throws JSONException {
    Bundle extra = new Bundle();
    extra.putString("json", json.toString());

    Intent notificationIntent = new Intent(activity, BeaconNotificationHandler.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("beacon", extra);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setDefaults(Notification.DEFAULT_ALL).setSmallIcon(context.getApplicationInfo().icon)
            .setWhen(System.currentTimeMillis()).setTicker(json.getString("title"))
            .setContentTitle(json.getString("message")).setContentIntent(contentIntent);

    String message = json.getString("message");
    if (message != null) {
        mBuilder.setContentText(message);
    } else {
        mBuilder.setContentText("<missing message content>");
    }
    mBuilder.addAction(context.getApplicationInfo().icon, json.getString("message"), contentIntent);

    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
            .notify((String) getAppName(context), NOTIFICATION_ID, mBuilder.build());
}

From source file:com.pinplanet.pintact.GcmIntentService.java

private void sendDefaultNotification() {
    Intent it = new Intent(this, LeftDeckActivity.class);
    it.putExtra(LeftDeckActivity.SELECTED_OPTIONS, LeftDeckActivity.OPTION_NOTIFY);
    // add the following line would show Pintact to the preview page.
    // it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Pintact Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText("New notification from Pintact"))
            .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
            .setContentText("New notification from Pintact");

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    SingletonLoginData.getInstance().mNotificationManager = mNotificationManager;
}

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

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Received start id " + startId + ": " + intent);
        if (intent != null) {
            try {
                params = new JSONObject(intent.getStringExtra("params"));
                headers = new JSONObject(intent.getStringExtra("headers"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from   ww  w  .  j  av a  2  s .  com
            }
            url = intent.getStringExtra("url");
            stationaryRadius = Float.parseFloat(intent.getStringExtra("stationaryRadius"));
            distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter"));
            scaledDistanceFilter = distanceFilter;
            desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy"));
            locationTimeout = Integer.parseInt(intent.getStringExtra("locationTimeout"));
            isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
            notificationTitle = intent.getStringExtra("notificationTitle");
            notificationText = intent.getStringExtra("notificationText");

            // Build a Notification required for running service in foreground.
            Intent main = new Intent(this, BackgroundGpsPlugin.class);
            main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            Notification.Builder builder = new Notification.Builder(this);
            builder.setContentTitle(notificationTitle);
            builder.setContentText(notificationText);
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
            builder.setContentIntent(pendingIntent);
            Notification notification;
            if (android.os.Build.VERSION.SDK_INT >= 16) {
                notification = buildForegroundNotification(builder);
            } else {
                notification = buildForegroundNotificationCompat(builder);
            }
            notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE
                    | Notification.FLAG_NO_CLEAR;
            startForeground(startId, notification);
        }
        Log.i(TAG, "- url: " + url);
        Log.i(TAG, "- params: " + params.toString());
        Log.i(TAG, "- headers: " + headers.toString());
        Log.i(TAG, "- stationaryRadius: " + stationaryRadius);
        Log.i(TAG, "- distanceFilter: " + distanceFilter);
        Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy);
        Log.i(TAG, "- locationTimeout: " + locationTimeout);
        Log.i(TAG, "- isDebugging: " + isDebugging);
        Log.i(TAG, "- notificationTitle: " + notificationTitle);
        Log.i(TAG, "- notificationText: " + notificationText);

        this.setPace(false);

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

From source file:at.bitfire.davdroid.syncadapter.SyncManager.java

@TargetApi(21)
public void performSync() {
    int syncPhase = SYNC_PHASE_PREPARE;
    try {//w  ww . ja va 2s .  c  o m
        App.log.info("Preparing synchronization");
        prepare();

        if (Thread.interrupted())
            return;
        syncPhase = SYNC_PHASE_QUERY_CAPABILITIES;
        App.log.info("Querying capabilities");
        queryCapabilities();

        syncPhase = SYNC_PHASE_PROCESS_LOCALLY_DELETED;
        App.log.info("Processing locally deleted entries");
        processLocallyDeleted();

        if (Thread.interrupted())
            return;
        syncPhase = SYNC_PHASE_PREPARE_DIRTY;
        App.log.info("Locally preparing dirty entries");
        prepareDirty();

        syncPhase = SYNC_PHASE_UPLOAD_DIRTY;
        App.log.info("Uploading dirty entries");
        uploadDirty();

        syncPhase = SYNC_PHASE_CHECK_SYNC_STATE;
        App.log.info("Checking sync state");
        if (checkSyncState()) {
            syncPhase = SYNC_PHASE_LIST_LOCAL;
            App.log.info("Listing local entries");
            listLocal();

            if (Thread.interrupted())
                return;
            syncPhase = SYNC_PHASE_LIST_REMOTE;
            App.log.info("Listing remote entries");
            listRemote();

            if (Thread.interrupted())
                return;
            syncPhase = SYNC_PHASE_COMPARE_LOCAL_REMOTE;
            App.log.info("Comparing local/remote entries");
            compareLocalRemote();

            syncPhase = SYNC_PHASE_DOWNLOAD_REMOTE;
            App.log.info("Downloading remote entries");
            downloadRemote();

            syncPhase = SYNC_PHASE_POST_PROCESSING;
            App.log.info("Post-processing");
            postProcess();

            syncPhase = SYNC_PHASE_SAVE_SYNC_STATE;
            App.log.info("Saving sync state");
            saveSyncState();
        } else
            App.log.info("Remote collection didn't change, skipping remote sync");

    } catch (IOException | ServiceUnavailableException e) {
        App.log.log(Level.WARNING, "I/O exception during sync, trying again later", e);
        syncResult.stats.numIoExceptions++;

        if (e instanceof ServiceUnavailableException) {
            Date retryAfter = ((ServiceUnavailableException) e).retryAfter;
            if (retryAfter != null) {
                // how many seconds to wait? getTime() returns ms, so divide by 1000
                syncResult.delayUntil = (retryAfter.getTime() - new Date().getTime()) / 1000;
            }
        }

    } catch (Exception | OutOfMemoryError e) {
        final int messageString;

        if (e instanceof UnauthorizedException) {
            App.log.log(Level.SEVERE, "Not authorized anymore", e);
            messageString = R.string.sync_error_unauthorized;
            syncResult.stats.numAuthExceptions++;
        } else if (e instanceof HttpException || e instanceof DavException) {
            App.log.log(Level.SEVERE, "HTTP/DAV Exception during sync", e);
            messageString = R.string.sync_error_http_dav;
            syncResult.stats.numParseExceptions++;
        } else if (e instanceof CalendarStorageException || e instanceof ContactsStorageException) {
            App.log.log(Level.SEVERE, "Couldn't access local storage", e);
            messageString = R.string.sync_error_local_storage;
            syncResult.databaseError = true;
        } else {
            App.log.log(Level.SEVERE, "Unknown sync error", e);
            messageString = R.string.sync_error;
            syncResult.stats.numParseExceptions++;
        }

        final Intent detailsIntent;
        if (e instanceof UnauthorizedException) {
            detailsIntent = new Intent(context, AccountSettingsActivity.class);
            detailsIntent.putExtra(AccountSettingsActivity.EXTRA_ACCOUNT, account);
        } else {
            detailsIntent = new Intent(context, DebugInfoActivity.class);
            detailsIntent.putExtra(DebugInfoActivity.KEY_THROWABLE, e);
            detailsIntent.putExtra(DebugInfoActivity.KEY_ACCOUNT, account);
            detailsIntent.putExtra(DebugInfoActivity.KEY_AUTHORITY, authority);
            detailsIntent.putExtra(DebugInfoActivity.KEY_PHASE, syncPhase);
        }

        // to make the PendingIntent unique
        detailsIntent.setData(Uri.parse("uri://" + getClass().getName() + "/" + uniqueCollectionId));

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.drawable.ic_error_light).setLargeIcon(App.getLauncherBitmap(context))
                .setContentTitle(getSyncErrorTitle())
                .setContentIntent(
                        PendingIntent.getActivity(context, 0, detailsIntent, PendingIntent.FLAG_CANCEL_CURRENT))
                .setCategory(NotificationCompat.CATEGORY_ERROR);

        try {
            String[] phases = context.getResources().getStringArray(R.array.sync_error_phases);
            String message = context.getString(messageString, phases[syncPhase]);
            builder.setContentText(message);
        } catch (IndexOutOfBoundsException ex) {
            // should never happen
        }

        notificationManager.notify(uniqueCollectionId, notificationId(), builder.build());
    }
}

From source file:org.kegbot.app.service.CheckinService.java

/**
 * Processes the checkin response message.
 *//*  w  w  w  .  java2 s .  c o m*/
private void processLastCheckinResponse(JsonNode response) {
    Log.d(TAG, "Checkin response: " + response);

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    final JsonNode statusNode = response.get("status");
    if (statusNode == null || !statusNode.isTextual()) {
        Log.d(TAG, "Invalid checkin response: no status.");
        return;
    }

    final String status = statusNode.getTextValue();
    if (STATUS_OK.equals(status)) {
        Log.d(TAG, "Checkin status: " + status);
    } else {
        Log.d(TAG, "Invalid checkin response: unknown status: " + status);
        return;
    }

    boolean updateNeeded = false;
    final JsonNode updateNeededNode = response.get("update_needed");
    if (updateNeededNode != null && updateNeededNode.isBoolean() && updateNeededNode.getBooleanValue()) {
        updateNeeded = true;
    }

    boolean updateRequired = false;
    final JsonNode updateRequiredNode = response.get("update_required");
    if (updateRequiredNode != null && updateRequiredNode.isBoolean() && updateRequiredNode.getBooleanValue()) {
        updateRequired = true;
    }

    mPrefsHelper.setLastCheckinStatus(status);
    mPrefsHelper.setUpdateNeeded(updateNeeded);
    mPrefsHelper.setUpdateRequired(updateRequired);

    if (updateNeeded) {
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse("market://details?id=org.kegbot.app"));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        int titleRes = updateRequired ? R.string.checkin_update_required_title
                : R.string.checkin_update_available_title;

        Notification noti = new Notification.Builder(this)
                .setSmallIcon(updateRequired ? R.drawable.icon_warning : R.drawable.icon_download)
                .setContentTitle(getString(titleRes))
                .setContentText(getString(R.string.checkin_update_description)).setContentIntent(contentIntent)
                .setOngoing(true).setOnlyAlertOnce(true).getNotification();

        Log.d(TAG, "Posting notification.");
        nm.notify(CHECKIN_NOTIFICATION_ID, noti);
    } else {
        nm.cancel(CHECKIN_NOTIFICATION_ID);
    }
}

From source file:io.coldstart.android.GCMIntentService.java

private void sendRateLimitNotification(String rateLimitCount) {
    if (null == rateLimitCount)
        rateLimitCount = "0";

    Intent intent = new Intent(this, TrapListActivity.class);
    intent.putExtra("forceDownload", true);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Intent broadcastDownload = new Intent();
    broadcastDownload.setAction(BatchDownloadReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastDownload = PendingIntent.getBroadcast(this, 0, broadcastDownload, 0);

    Intent broadcastIgnore = new Intent();
    broadcastIgnore.setAction(BatchIgnoreReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastIgnore = PendingIntent.getBroadcast(this, 0, broadcastIgnore, 0);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Notification notification = null;

    if (Build.VERSION.SDK_INT >= 16) {
        notification = new Notification.InboxStyle(new Notification.Builder(this)
                .setContentTitle("Inbound Traps have been rate limited")
                .setContentText(//  w w w  .  ja  va2s.co  m
                        "\"The number of traps being relayed to your phone has breeched the rate limit.")
                .setSmallIcon(R.drawable.ic_stat_ratelimit).setVibrate(new long[] { 0, 100, 200, 300 })
                .setAutoCancel(true).setSound(uri).setPriority(Notification.PRIORITY_HIGH)
                .setTicker("Inbound Traps have been rate limited")
                .addAction(R.drawable.ic_download_batch, "Get Batched Traps", pBroadcastDownload)
                .addAction(R.drawable.ic_ignore, "Ignore Batch", pBroadcastIgnore))
                        .setBigContentTitle("Inbound Traps have been rate limited")
                        .setSummaryText("Launch ColdStart.io to Manage These Events")
                        .addLine("The number of traps relayed to you has breeched the rate limit.")
                        .addLine("The current number of items queued is " + rateLimitCount).addLine(" ")
                        .addLine("Tap \"Get Batched Traps\" to download the cached traps")
                        .addLine("Tap \"Ignore Batch\" to delete them from the server.")

                        .build();
    } else {
        notification = new Notification.Builder(this).setContentTitle("Inbound Traps have been rate limited")
                .setContentText(
                        "The number of traps being relayed to your phone has breeched the rate limit. The current number of items queued is "
                                + rateLimitCount
                                + "\nTap \"Get Alerts\" to batch download the outstanding traps or tap \"Ignore\" to delete them from the server.")
                .setSmallIcon(R.drawable.ic_stat_ratelimit).setContentIntent(pIntent)
                .setVibrate(new long[] { 0, 100, 200, 300 }).setAutoCancel(true).setSound(uri).build();
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(43524, notification);
}

From source file:com.github.play.app.StatusService.java

private void updateNotification(Song song) {
    if (!sendNotification)
        return;/*from  ww  w  . ja  v a  2s.  com*/

    Context context = getApplicationContext();
    PendingIntent intent = PendingIntent.getActivity(context, 0, new Intent(context, PlayActivity.class),
            FLAG_UPDATE_CURRENT);

    Notification notification;
    if (SDK_INT >= JELLY_BEAN)
        notification = createBigNotification(context, song, intent);
    else
        notification = createNotification(context, song, intent);

    if (notificationSent)
        getNotificationManager().notify(1, notification);
    else {
        notificationSent = true;
        startForeground(1, notification);
    }
}

From source file:com.vendsy.bartsy.venue.GCMIntentService.java

/**
 * To generate a notification to inform the user that server has sent a message.
 * /*from w  ww  .jav a2  s. co  m*/
 * @param count
 * @param count 
 */
private static void generateNotification(Context context, String message, String count) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MainActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    try {
        int countValue = Integer.parseInt(count);
        notification.number = countValue;
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    // // Play default notification sound
    notification.defaults = Notification.DEFAULT_SOUND;
    notificationManager.notify(0, notification);
}

From source file:com.perm.DoomPlay.PlayingService.java

private Notification createNotification() {

    Intent intentActivity;//w ww . j av  a2  s.c o  m

    if (SettingActivity.getPreferences(SettingActivity.keyOnClickNotif)) {
        intentActivity = new Intent(FullPlaybackActivity.actionReturnFull);
        intentActivity.setClass(this, FullPlaybackActivity.class);
        intentActivity.putExtra(FileSystemActivity.keyMusic, audios);
    } else {
        intentActivity = FullPlaybackActivity.getReturnSmallIntent(this, audios);
    }
    intentActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    Notification notification = new Notification();
    notification.contentView = getNotifViews(R.layout.notif);
    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
    notification.contentIntent = PendingIntent.getActivity(this, 0, intentActivity,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.icon = isPlaying ? R.drawable.status_icon_pause : R.drawable.status_icon_play;

    return notification;
}

From source file:gpsalarm.app.service.PostMonitor.java

private void showProximityNotification(String string) {
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification note = new Notification(R.drawable.status, "Friend@ notification!",
            System.currentTimeMillis());
    Intent i = new Intent(this, AlertList.class);

    //      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
    //                      Intent.FLAG_ACTIVITY_SINGLE_TOP);
    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
    note.setLatestEventInfo(this, "Friend@ notification", string, pi);

    mgr.notify(NOTIFICATION_ID, note);//from w ww  .ja va  2  s.com

}