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:com.example.mynsocial.BluetoothChat.java

public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    Log.i(TAG, "---------------------------------------");
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent,
            0);// w  ww.ja  va  2s.c  o m
    String[][] techList = new String[][] {};
    adapter.enableForegroundDispatch(activity, pendingIntent, null, techList);
}

From source file:com.flowzr.export.flowzr.FlowzrSyncEngine.java

public static String create(Context p_context, DatabaseAdapter p_dba, DefaultHttpClient p_http) {
    startTimestamp = System.currentTimeMillis();

    if (isRunning == true) {
        isCanceled = true;/*from w  ww . jav  a  2s. c o m*/
        isRunning = false;
    }
    isRunning = true;
    boolean recordSyncTime = true;

    dba = p_dba;
    db = dba.db();
    em = dba.em();
    http_client = p_http;
    context = p_context;

    last_sync_ts = MyPreferences.getFlowzrLastSync(context);
    FLOWZR_BASE_URL = "https://" + MyPreferences.getSyncApiUrl(context);
    FLOWZR_API_URL = FLOWZR_BASE_URL + "/financisto3/";

    nsString = MyPreferences.getFlowzrAccount(context).replace("@", "_"); //urlsafe

    Log.i(TAG, "init sync engine, last sync was " + new Date(last_sync_ts).toLocaleString());
    //if (true) {
    if (!checkSubscriptionFromWeb()) {
        Intent notificationIntent = new Intent(context, FlowzrSyncActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon)
                .setTicker(context.getString(R.string.flowzr_subscription_required))
                .setContentTitle(context.getString(R.string.flowzr_sync_error))
                .setContentText(context.getString(R.string.flowzr_subscription_required,
                        MyPreferences.getFlowzrAccount(context)))
                .setContentIntent(pendingIntent).setAutoCancel(true).build();
        notificationManager.notify(0, notification);

        Log.w("flowzr", "subscription rejected from web");
        isCanceled = true;
        MyPreferences.unsetAutoSync(context);
        return null;
    } else {
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        // Sets an ID for the notification, so it can be updated

        mNotifyBuilder = new NotificationCompat.Builder(context).setAutoCancel(true)
                .setContentTitle(context.getString(R.string.flowzr_sync))
                .setContentText(context.getString(R.string.flowzr_sync_inprogress))
                .setSmallIcon(R.drawable.icon);
    }

    if (!isCanceled) {
        notifyUser("fix created entities", 5);
        fixCreatedEntities();
    }
    /**
     * pull delete
     */
    if (!isCanceled) {
        notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 10);
        try {
            pullDelete(last_sync_ts);
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }
    /**
     * push delete
     */
    if (!isCanceled) {
        notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 15);
        try {
            pushDelete();
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }
    /**
     * pull update
     */
    if (!isCanceled && last_sync_ts == 0) {
        notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20);
        try {
            pullUpdate();
        } catch (IOException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (JSONException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }
    /**
     * push update
     */
    if (!isCanceled) {
        notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 35);
        try {
            pushUpdate();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (IOException e) {
            e.printStackTrace();
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (JSONException e) {
            e.printStackTrace();
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (Exception e) {
            e.printStackTrace();
            recordSyncTime = false;
        }
    }
    /**
     * pull update
     */
    if (!isCanceled && last_sync_ts > 0) {
        notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20);
        try {
            pullUpdate();
        } catch (IOException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (JSONException e) {
            sendBackTrace(e);
            recordSyncTime = false;
        } catch (Exception e) {
            sendBackTrace(e);
            recordSyncTime = false;
        }
    }

    notifyUser(context.getString(R.string.integrity_fix), 80);
    new IntegrityFix(dba).fix();
    /**
     * send account balances boundaries
     */
    if (!isCanceled) {
        //if (true) { //will generate a Cloud Messaging request if prev. aborted        
        notifyUser(context.getString(R.string.flowzr_sync_sending) + "...", 85);
        //nm.notify(NOTIFICATION_ID, mNotifyBuilder.build()); 
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("action", "balancesRecalc"));
        nameValuePairs.add(new BasicNameValuePair("last_sync_ts", String.valueOf(last_sync_ts)));

        String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL
                : Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        nameValuePairs.add(new BasicNameValuePair("serialNumber", serialNumber));
        List<Account> accountsList = em.getAllAccountsList();
        for (Account account : accountsList) {
            nameValuePairs.add(new BasicNameValuePair(account.remoteKey, String.valueOf(account.totalAmount)));
            Log.i("flowzr", account.remoteKey + " " + String.valueOf(account.totalAmount));
        }
        try {
            httpPush(nameValuePairs, "balances");
        } catch (Exception e) {
            sendBackTrace(e);
        }
    }

    notifyUser("Widgets ...", 90);
    AccountWidget.updateWidgets(context);

    Handler refresh = new Handler(Looper.getMainLooper());
    refresh.post(new Runnable() {
        public void run() {
            if (currentActivity != null) {
                //currentActivity.refreshCurrentTab();
            }
        }
    });

    if (!isCanceled && MyPreferences.doGoogleDriveUpload(context)) {
        notifyUser(context.getString(R.string.flowzr_sync_sending) + " Google Drive", 95);
        pushAllBlobs();
    } else {
        Log.i("flowzr", "picture upload desactivated in prefs");
    }
    notifyUser(context.getString(R.string.flowzr_sync_success), 100);
    if (isCanceled == false) {
        if (recordSyncTime == true) {
            last_sync_ts = System.currentTimeMillis();
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
            editor.putLong("PROPERTY_LAST_SYNC_TIMESTAMP", last_sync_ts);
            editor.commit();
        }
    }
    //
    mNotificationManager.cancel(NOTIFICATION_ID);
    isRunning = false;
    isCanceled = false;
    if (context instanceof FlowzrSyncActivity) {
        ((FlowzrSyncActivity) context).setIsFinished();
    }
    return FLOWZR_BASE_URL;

}

From source file:com.sublimis.urgentcallfilter.Magic.java

@SuppressWarnings("deprecation")
private void notification() {
    if (MyPreference.isNotifications()) {
        if (mContext != null) {
            NotificationManager notificationManager = (NotificationManager) mContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);

            if (notificationManager != null) {
                Notification notification = new Notification(R.drawable.icon, null, System.currentTimeMillis());
                Intent notificationIntent = new Intent(mContext, ActivityMain.class);

                if (notification != null && notificationIntent != null) {
                    notificationIntent.setFlags(notificationIntent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

                    notification.setLatestEventInfo(mContext,
                            mContext.getResources().getString(R.string.notification_title),
                            mContext.getResources().getString(R.string.notification_text), pendingIntent);

                    notificationManager.notify(0, notification);
                }// w  ww .  j  a  v a 2s .  co  m
            }
        }
    }
}

From source file:be.vbsteven.bmtodesk.BackgroundSharingService.java

/**
 * shows notification when the sending succeeded
 */// w  w  w.  j a v  a2s .  c om
private void showSuccessfulSend() {
    if (Global.isHideConfirmation(this)) {
        nManager.cancelAll();
    } else {
        Notification n = new Notification(R.drawable.icon, "Sending bookmark successful",
                System.currentTimeMillis());
        n.flags = Notification.FLAG_AUTO_CANCEL;
        Intent i = new Intent(this, AfterSuccessfulSendActivity.class);
        i.putExtra(Global.EXTRA_TITLE, title);
        i.putExtra(Global.EXTRA_URL, url);
        PendingIntent p = PendingIntent.getActivity(this, 4, i, 0);
        n.setLatestEventInfo(this, "Bookmark to Desktop", "Sending bookmark successful", p);
        nManager.notify(3, n);
    }
}

From source file:com.jaguarlandrover.auto.remote.vehicleentry.RviService.java

static void sendNotification(Context ctx, String action, String... extras) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    boolean fire = prefs.getBoolean("pref_fire_notifications", true);

    if (!fire)//from www  .  j a  v a 2 s.c o m
        return;

    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx).setSmallIcon(R.drawable.rvi_not)
            .setAutoCancel(true).setContentTitle(ctx.getResources().getString(R.string.app_name))
            .setContentText(action);

    Intent targetIntent = new Intent(ctx, LockActivity.class);
    int j = 0;
    for (String ex : extras) {
        targetIntent.putExtra("_extra" + (++j), ex);
        targetIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    }
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, targetIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    nm.notify(0, builder.build());
}

From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java

private static void issueNotification(Context context, Set<String> addedMilestones,
        Set<String> removedMilestones, Map<String, int[]> changedProgresses) {
    String title = context.getString(R.string.notification_title);
    StringBuilder message = new StringBuilder();

    // Changed progresses
    for (String milestoneTitle : changedProgresses.keySet()) {
        int oldProgress = changedProgresses.get(milestoneTitle)[0];
        int newProgress = changedProgresses.get(milestoneTitle)[1];
        message.append("\n").append(String.format(context.getString(R.string.notific_msg_text_format),
                milestoneTitle, oldProgress, newProgress));
    }//from w  w  w. j a va  2 s.co  m

    // Added milestones
    for (String milestoneTitle : addedMilestones) {
        message.append("\n").append(context.getString(R.string.milestone_added_notification, milestoneTitle));
    }

    // Removed milestones
    for (String milestoneTitle : removedMilestones) {
        message.append("\n").append(context.getString(R.string.milestone_removed_notification, milestoneTitle));
    }

    // Remove first newline
    message.delete(0, 1);

    // Create PendingIntent
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean sound = pref.getBoolean(Constants.NOTIFICATION_SOUND_PREF, true);
    boolean vibrate = pref.getBoolean(Constants.NOTIFICATION_VIBRATE_PREF, true);
    boolean light = pref.getBoolean(Constants.NOTIFICATION_LIGHT_PREF, true);
    int defaults = 0;
    if (sound)
        defaults = defaults | Notification.DEFAULT_SOUND;
    if (vibrate)
        defaults = defaults | Notification.DEFAULT_VIBRATE;
    if (light)
        defaults = defaults | Notification.DEFAULT_LIGHTS;

    // Build the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(pendingIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setSmallIcon(R.mipmap.notification_small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setDefaults(defaults).setAutoCancel(true);

    // Issue the notification
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(PROGRESS_NOTIFICATION_ID, builder.build());
}

From source file:net.kourlas.voipms_sms.Notifications.java

public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
        Conversation[] conversations = Database.getInstance(applicationContext)
                .getConversations(preferences.getDid());
        for (Conversation conversation : conversations) {
            if (!conversation.isUnread() || !contacts.contains(conversation.getContact())
                    || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                            && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                                    .getContact().equals(conversation.getContact()))) {
                continue;
            }/*  w w w  .  j  a  v  a  2s.  c  o m*/

            String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
            if (smsContact == null) {
                smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
            }

            String allSmses = "";
            String mostRecentSms = "";
            boolean initial = true;
            for (Message message : conversation.getMessages()) {
                if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
                    if (initial) {
                        allSmses = message.getText();
                        mostRecentSms = message.getText();
                        initial = false;
                    } else {
                        allSmses = message.getText() + "\n" + allSmses;
                    }
                } else {
                    break;
                }
            }

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext);

            notificationBuilder.setContentTitle(smsContact);
            notificationBuilder.setContentText(mostRecentSms);
            notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
            notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
            notificationBuilder
                    .setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
            notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
            if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
                notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
            } else {
                notificationBuilder.setVibrate(new long[] { 0 });
            }
            notificationBuilder.setColor(0xFFAA0000);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

            Bitmap largeIconBitmap;
            try {
                largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                        Uri.parse(Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
                largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
                largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
                notificationBuilder.setLargeIcon(largeIconBitmap);
            } catch (Exception ignored) {

            }

            Intent intent = new Intent(applicationContext, ConversationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
            stackBuilder.addParentStack(ConversationActivity.class);
            stackBuilder.addNextIntent(intent);
            notificationBuilder
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

            Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
            } else {
                //noinspection deprecation
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            }
            replyIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent replyPendingIntent = PendingIntent.getActivity(applicationContext, 0, replyIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_reply_white_24dp,
                    applicationContext.getString(R.string.notifications_button_reply), replyPendingIntent);
            notificationBuilder.addAction(replyAction.build());

            Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
            markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast(applicationContext, 0,
                    markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_drafts_white_24dp,
                    applicationContext.getString(R.string.notifications_button_mark_read),
                    markAsReadPendingIntent);
            notificationBuilder.addAction(markAsReadAction.build());

            int id;
            if (notificationIds.get(conversation.getContact()) != null) {
                id = notificationIds.get(conversation.getContact());
            } else {
                id = notificationIdCount++;
                notificationIds.put(conversation.getContact(), id);
            }
            NotificationManager notificationManager = (NotificationManager) applicationContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}

From source file:de.hackerspacebremen.push.PushIntentService.java

public void displayNotification(final Context context, final SpaceData data, final boolean vibrationEnabled,
        final boolean permanentNotification) throws JSONException {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);

    final boolean permanent = permanentNotification && data.isSpaceOpen();

    String timeString = context.getString(R.string.unknown);
    Date time = data.getTime();/* w  ww  .  ja  va  2s  .  c om*/
    if (time != null) {
        timeString = SpeakingDateFormat.format(time);
    }

    int icon;
    CharSequence notificationText;
    final CharSequence contentTitle;
    if (data.isSpaceOpen()) {
        icon = R.drawable.notification_open;
        notificationText = context.getString(R.string.space_open, timeString);
        contentTitle = context.getString(R.string.space_open_simple);
    } else {
        icon = R.drawable.notification_closed;
        notificationText = context.getString(R.string.space_closed, timeString);
        contentTitle = context.getString(R.string.space_closed_simple);
    }

    long when = System.currentTimeMillis();

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(icon);
    builder.setTicker(notificationText);
    builder.setWhen(when);
    if (data.getMessage() != null && data.getMessage().length() > 0) {
        builder.setStyle(new NotificationCompat.BigTextStyle().setSummaryText(notificationText)
                .bigText("Nachricht: \n" + data.getMessage()));
    }
    if (!permanent) {
        builder.setAutoCancel(true);
    }
    builder.setContentTitle(contentTitle);
    builder.setContentText(notificationText);
    Intent notificationIntent = new Intent(context, StartActivity.class);
    notificationIntent.putExtra("status_json", SpaceDataJsonParser.parse(data).toString());
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    builder.setContentIntent(contentIntent);

    final Notification notification = builder.build();
    if (vibrationEnabled) {
        notification.defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (permanent) {
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
    }
    mNotificationManager.notify(Constants.NOTIFICATION_ID, notification);
}

From source file:fi.iki.murgo.irssinotifier.SettingsActivity.java

private void handleColorPicker() {
    Preference colorPickerPref = findPreference("PickCustomLightColor");
    colorPickerPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override/*from w w w . j a  va2  s . c  om*/
        public boolean onPreferenceClick(final Preference preference) {
            final Context ctx = SettingsActivity.this;

            final Preferences preferences = new Preferences(ctx);
            final int color = preferences.getCustomLightColor();

            NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
            builder.setSmallIcon(R.drawable.notification_icon);
            builder.setTicker("Preview selected color");
            builder.setAutoCancel(false);
            builder.setOngoing(false);
            builder.setContentText("Wait for the screen to turn off to see selected light color in action");
            builder.setContentTitle("Preview light color");
            builder.setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0));
            builder.setLights(color, 300, 5000);

            final Notification notification = builder.build();
            final NotificationManager notificationManager = (NotificationManager) ctx
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(666, notification);

            final AmbilWarnaDialog dialog = new AmbilWarnaDialog(ctx, color,
                    new AmbilWarnaDialog.OnAmbilWarnaListener() {
                        @Override
                        public void onCancel(AmbilWarnaDialog dialog) {
                            notificationManager.cancel(666);
                        }

                        @Override
                        public void onOk(AmbilWarnaDialog dialog, int color) {
                            notificationManager.cancel(666);
                            preferences.setCustomLightColor(color);
                        }

                        @Override
                        public void onColorChanged(AmbilWarnaDialog dialog, int color) {
                            notification.ledARGB = color;
                            notificationManager.notify(666, notification);
                        }
                    });

            dialog.show();

            return true;
        }
    });
}