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.freshplanet.nativeExtensions.C2DMBroadcastReceiver.java

/**
 * Get the parameters from the message and create a notification from it.
 * @param context//from  w  w  w .ja  v  a  2  s . com
 * @param intent
 */
public void handleMessage(Context context, Intent intent) {
    try {
        registerResources(context);
        extractColors(context);

        FREContext ctxt = C2DMExtension.context;

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // icon is required for notification.
        // @see http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html

        int icon = notificationIcon;
        long when = System.currentTimeMillis();

        // json string

        String parameters = intent.getStringExtra("parameters");
        String facebookId = null;
        JSONObject object = null;
        if (parameters != null) {
            try {
                object = (JSONObject) new JSONTokener(parameters).nextValue();
            } catch (Exception e) {
                Log.d(TAG, "cannot parse the object");
            }
        }
        if (object != null && object.has("facebookId")) {
            facebookId = object.getString("facebookId");
        }

        CharSequence tickerText = intent.getStringExtra("tickerText");
        CharSequence contentTitle = intent.getStringExtra("contentTitle");
        CharSequence contentText = intent.getStringExtra("contentText");

        Intent notificationIntent = new Intent(context, Class.forName(context.getPackageName() + ".AppEntry"));

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

        Notification notification = new Notification(icon, tickerText, when);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        RemoteViews contentView = new RemoteViews(context.getPackageName(), customLayout);

        contentView.setTextViewText(customLayoutTitle, contentTitle);
        contentView.setTextViewText(customLayoutDescription, contentText);

        contentView.setTextColor(customLayoutTitle, notification_text_color);
        contentView.setFloat(customLayoutTitle, "setTextSize",
                notification_title_size_factor * notification_text_size);
        contentView.setTextColor(customLayoutDescription, notification_text_color);
        contentView.setFloat(customLayoutDescription, "setTextSize",
                notification_description_size_factor * notification_text_size);

        if (facebookId != null) {
            Log.d(TAG, "bitmap not null");
            CreateNotificationTask cNT = new CreateNotificationTask();
            cNT.setParams(customLayoutImageContainer, NotifId, nm, notification, contentView);
            String src = "http://graph.facebook.com/" + facebookId + "/picture?type=normal";
            URL url = new URL(src);
            cNT.execute(url);
        } else {
            Log.d(TAG, "bitmap null");
            contentView.setImageViewResource(customLayoutImageContainer, customLayoutImage);
            notification.contentView = contentView;
            nm.notify(NotifId, notification);
        }
        NotifId++;

        if (ctxt != null) {
            parameters = parameters == null ? "" : parameters;
            ctxt.dispatchStatusEventAsync("COMING_FROM_NOTIFICATION", parameters);
        }

    } catch (Exception e) {
        Log.e(TAG, "Error activating application:", e);
    }
}

From source file:com.securekey.sdk.sample.ReadCardActivity.java

private void enableForegroundDispatch() {
    Log.i("SDKSample", "enable foreground dispatch");
    if (NfcAdapter.getDefaultAdapter(this) != null) {
        try {/*from w  w w  . ja v a2 s .  co  m*/
            NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this,
                    PendingIntent.getActivity(this, 0,
                            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0),
                    new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) }, new String[][] {
                            new String[] { NfcA.class.getName() }, new String[] { NfcB.class.getName() } });
        } catch (Exception e) {
            Log.i("SDKSample", "enableForegroundDispatch failed");
        }
    }
}

From source file:com.amazon.cordova.plugin.ADMMessageHandler.java

/**
 * Creates a notification when app is not running or is not in foreground. It puts the message info into the Intent
 * extra//from w  ww .  ja va 2  s . co m
 * 
 * @param context
 * @param extras
 */
public void createNotification(Context context, Bundle extras) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    String appName = getAppName(this);

    // reuse the intent so that we can combine multiple messages into extra
    if (notificationIntent == null) {
        notificationIntent = new Intent(this, ADMHandlerActivity.class);
    }
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("pushBundle", extras);

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

    final Builder notificationBuilder = new Notification.Builder(context);
    notificationBuilder.setSmallIcon(context.getApplicationInfo().icon).setWhen(System.currentTimeMillis())
            .setContentIntent(contentIntent);

    if (this.shouldShowMessageInNotification()) {
        String message = extras.getString(PushPlugin.MESSAGE);
        notificationBuilder.setContentText(Html.fromHtml(message).toString());
    } else {
        notificationBuilder.setContentText(this.defaultMessageTextInNotification());
    }

    String title = appName;
    notificationBuilder.setContentTitle(title).setTicker(title);
    notificationBuilder.setAutoCancel(true);
    // Because the ID remains unchanged, the existing notification is updated.
    notificationManager.notify((String) appName, NOTIFICATION_ID, notificationBuilder.getNotification());
}

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

private void sendBatchNotification(String batchCount) {
    if (null == batchCount)
        batchCount = "1+";

    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("A batch of Traps has been sent")
                        .setContentText("\"Batched traps are waiting to be downloaded")
                        .setSmallIcon(R.drawable.ic_stat_ratelimit).setVibrate(new long[] { 0, 100, 200, 300 })
                        .setAutoCancel(true).setSound(uri).setPriority(Notification.PRIORITY_HIGH)
                        .setTicker("A batch of Traps has been sent")
                        .addAction(R.drawable.ic_download_batch, "Get Batched Traps", pBroadcastDownload)
                        .addAction(R.drawable.ic_ignore, "Ignore Batch", pBroadcastIgnore))
                                .setBigContentTitle("A batch of Traps has been sent")
                                .setSummaryText("Launch ColdStart.io to Manage These Events")
                                .addLine("A number of traps have been sent and batched for delivery")
                                .addLine("The current number of items queued is " + batchCount).addLine(" ")
                                .addLine("Tap \"Get Batched Traps\" to download the cached traps")
                                .addLine("Tap \"Ignore Batch\" to delete them from the server.")

                                .build();
    } else {//from   w w  w .  j  a  va2  s.co  m
        notification = new Notification.Builder(this).setContentTitle("A batch of Traps has been sent")
                .setContentText(
                        "A number of traps have been sent and batched for delivery. The current number of items queued is "
                                + batchCount
                                + "\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.ibm.bluelist.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    SensoroManager sensoroManager = SensoroManager.getInstance(getApplicationContext());
    blApplication = (MessengerApplication) getApplication();
    if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();//www .  ja  v  a  2s .c o m
    }
    myIntent = new Intent(getApplicationContext(), PostTrackingNotifier.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    if (sensoroManager.isBluetoothEnabled()) {
        /**
         * Enable cloud service (upload sensor data, including battery status, UMM, etc.)Without setup, it keeps in closed status as default.
         **/
        sensoroManager.setCloudServiceEnable(true);
        /**
         * Enable SDK service
         **/
        try {
            sensoroManager.startService();
        } catch (Exception e) {
            e.printStackTrace(); // Fetch abnormal info
        }
    } else {
        Intent bluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(bluetoothIntent, REQUEST_ENABLE_BT);
    }
    BeaconManagerListener beaconManagerListener = new BeaconManagerListener() {
        ArrayList<String> foundSensors = new ArrayList<String>();

        @Override
        public void onUpdateBeacon(ArrayList<Beacon> beacons) {
            // Refresh sensor info
            for (Beacon beacon : beacons) {
                if (true) {
                    if (beacon.getMovingState() == Beacon.MovingState.DISABLED) {
                        // Disable accelerometer
                        System.out.println(beacon.getSerialNumber() + "Disabled");
                        Log.d("Main", beacon.getSerialNumber() + "Disabled");

                    } else if (beacon.getMovingState() == Beacon.MovingState.STILL) {
                        // Device is at static
                        Log.d("Main", beacon.getSerialNumber() + "static");
                        Log.d("Main", beacon.getProximityUUID());
                        if (!foundSensors.contains(beacon.getProximityUUID())) {
                            //String messageDisplay = "";
                            Log.d("Main", "getting Beacon Info");
                            foundSensors.add(beacon.getProximityUUID());
                            IBMCloudCode.initializeService();
                            IBMCloudCode myCloudCodeService = IBMCloudCode.getService();
                            String id = beacon.getProximityUUID();
                            String url = "/getNotification?id=" + id;
                            myCloudCodeService.get(url).continueWith(new Continuation<IBMHttpResponse, Void>() {

                                @Override
                                public Void then(Task<IBMHttpResponse> task) throws Exception {
                                    if (task.isCancelled()) {
                                        Log.e(CLASS_NAME,
                                                "Exception : Task" + task.isCancelled() + "was cancelled.");
                                    } else if (task.isFaulted()) {
                                        Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                                    } else {
                                        InputStream is = task.getResult().getInputStream();
                                        try {
                                            BufferedReader in = new BufferedReader(new InputStreamReader(is));
                                            String responseString = "";
                                            String myString = "";
                                            while ((myString = in.readLine()) != null)
                                                responseString += myString;

                                            in.close();
                                            Log.i(CLASS_NAME, "Response Body: " + responseString);
                                            JSONObject obj = new JSONObject(responseString);
                                            final String name = obj.getString("message");
                                            final String meets = obj.getString("meetups");

                                            /*Notification*/

                                            myIntent.putExtra("response", responseString);
                                            PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
                                                    getApplicationContext(), 5, myIntent,
                                                    PendingIntent.FLAG_UPDATE_CURRENT);
                                            final NotificationCompat.Builder builder = new NotificationCompat.Builder(
                                                    getApplicationContext());
                                            builder.setSmallIcon(R.drawable.logo);
                                            builder.setContentTitle("IBM Beacons Messenger");
                                            builder.setContentText(name);
                                            builder.setContentIntent(pendingNotificationIntent);
                                            NotificationManager notificationManager = (NotificationManager) getSystemService(
                                                    Context.NOTIFICATION_SERVICE);
                                            notificationManager.notify(5, builder.build());

                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }

                                        Log.i(CLASS_NAME, "Response Status from login: "
                                                + task.getResult().getHttpResponseCode());
                                    }

                                    return null;
                                }

                            });

                        }
                        Log.d("Main", beacon.getMajor().toString());
                        Log.d("Main", beacon.getMinor().toString());
                        //Log.d("Main",beacon.getRssi().toString());
                        System.out.println(beacon.getSerialNumber() + "static");

                    } else if (beacon.getMovingState() == Beacon.MovingState.MOVING) {
                        // Device is moving
                        Log.d("Main", beacon.getSerialNumber() + "moving");
                        Log.d("Main", beacon.getProximityUUID());
                        System.out.println(beacon.getSerialNumber() + "moving");
                    }
                }
            }
        }

        @Override
        public void onNewBeacon(Beacon beacon) {
            // New sensor found
            System.out.println(beacon.getSerialNumber());
            Log.d("Main", beacon.getSerialNumber() + "Got New");
        }

        @Override
        public void onGoneBeacon(Beacon beacon) {
            // A sensor disappears from the range
            System.out.println(beacon.getSerialNumber());

        }
    };
    sensoroManager.setBeaconManagerListener(beaconManagerListener);
}

From source file:org.lol.reddit.receivers.NewMessageChecker.java

private static void createNotification(String title, String text, Context context) {

    final NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.icon_inv).setContentTitle(title).setContentText(text).setAutoCancel(true);

    final Intent intent = new Intent(context, InboxListingActivity.class);
    notification.setContentIntent(PendingIntent.getActivity(context, 0, intent, 0));

    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(0, notification.getNotification());
}

From source file:com.snappy.GCMIntentService.java

@SuppressWarnings("deprecation")
public void triggerNotification(Context context, String message, String fromName, Bundle pushExtras,
        String messageData) {//from   w ww  . j a  v  a 2  s .c  o m

    if (fromName != null) {
        final NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);

        Notification notification = new Notification(R.drawable.icon_notification, message,
                System.currentTimeMillis());

        notification.number = mNotificationCounter + 1;
        mNotificationCounter = mNotificationCounter + 1;

        Intent intent = new Intent(this, SplashScreenActivity.class);
        intent.replaceExtras(pushExtras);
        intent.putExtra(Const.PUSH_INTENT, true);
        intent.setAction(Long.toString(System.currentTimeMillis()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND
                | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, notification.number, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this, context.getString(R.string.app_name), messageData, pendingIntent);

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        String notificationId = Double.toString(Math.random());
        notificationManager.notify(notificationId, 0, notification);

    }

    Log.i(LOG_TAG, message);
    Log.i(LOG_TAG, fromName);

}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

private void handleResponse() {
    Log.i(this.getClass().getName(), "in handleResponse()");
    // close progress notification
    mNotificationManager.cancel(NOTIFICATION_ID);

    String notificationMessage = getString(R.string.upload_success);

    // notification intent with result
    final Intent notificationIntent = new Intent(getBaseContext(), ImageDetails.class);

    if (mImgurResponse == null) {
        notificationMessage = getString(R.string.connection_failed);
    } else if (mImgurResponse.get("error") != null) {
        notificationMessage = getString(R.string.unknown_error) + mImgurResponse.get("error");
    } else {/* w w w . j  a va 2 s . com*/
        // create thumbnail
        if (mImgurResponse.get("image_hash").length() > 0) {
            createThumbnail(imageLocation);
        }

        // store result in database
        final HistoryDatabase histData = new HistoryDatabase(getBaseContext());
        final SQLiteDatabase data = histData.getWritableDatabase();

        final HashMap<String, String> dataToSave = new HashMap<String, String>();
        dataToSave.put("delete_hash", mImgurResponse.get("delete_hash"));
        dataToSave.put("image_url", mImgurResponse.get("original"));
        final Uri imageUri = Uri
                .parse(getFilesDir() + "/" + mImgurResponse.get("image_hash") + THUMBNAIL_POSTFIX);
        dataToSave.put("local_thumbnail", imageUri.toString());
        dataToSave.put("upload_time", "" + System.currentTimeMillis());

        for (final Map.Entry<String, String> entry : dataToSave.entrySet()) {
            final ContentValues content = new ContentValues();
            content.put("hash", mImgurResponse.get("image_hash"));
            content.put("key", entry.getKey());
            content.put("value", entry.getValue());
            data.insert("imgur_history", null, content);
        }

        //set intent to go to image details
        notificationIntent.putExtra("hash", mImgurResponse.get("image_hash"));
        notificationIntent.putExtra("image_url", mImgurResponse.get("original"));
        notificationIntent.putExtra("delete_hash", mImgurResponse.get("delete_hash"));
        notificationIntent.putExtra("local_thumbnail", imageUri.toString());

        data.close();
        histData.close();

        // if the main activity is already open then refresh the gridview
        sendBroadcast(new Intent(BROADCAST_ACTION));
    }

    //assemble notification
    final Notification notification = new Notification(R.drawable.icon, notificationMessage,
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, getString(R.string.app_name), notificationMessage, PendingIntent
            .getActivity(getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

}

From source file:com.commontime.plugin.notification.notification.Builder.java

/**
 * Set intent to handle the action click event. Will bring the app to
 * foreground./*from w w w.j  av a 2  s.c o m*/
 *
 * @param builder
 *      Local notification builder instance
 */
private void applyActionReceiver(NotificationCompat.Builder builder) {

    if (actionClickActivity == null)
        return;

    try {
        for (int i = 0; i < options.getCategoryActionCount(); i++) {
            JSONObject action = options.getCategoryAction(i);

            Intent intent = new Intent(context, actionClickActivity).putExtra(Options.EXTRA, options.toString())
                    .putExtra(ActionClickActivity.ACTION_PARAM, action.toString())
                    .setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            int requestCode = new Random().nextInt();

            PendingIntent actionIntent = PendingIntent.getActivity(context, requestCode, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            builder.addAction(new NotificationCompat.Action(
                    context.getResources().getIdentifier("action_hand", "drawable", context.getPackageName()),
                    action.getString("title"), actionIntent));
        }
    } catch (Exception e) {
    }
}

From source file:ar.com.martinrevert.argenteam.GcmIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from w  w  w . j ava 2 s  . co m*/
private void generarNotification(Context context, String message, String urlimagen, String urlarticulo,
        String tipo, String fecha) {
    SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean vib = preferencias.getBoolean("vibraoff", false);
    boolean movieoff = preferencias.getBoolean("movieoff", false);
    boolean tvoff = preferencias.getBoolean("tvoff", false);
    String ringmovie = preferencias.getString("prefRingtonemovie", "");
    String ringtv = preferencias.getString("prefRingtonetv", "");
    //Todo traducir ticker
    String ticker = "Nuevo subttulo " + tipo + " en aRGENTeaM";

    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(100);

    Bitmap bitmap = getRemoteImage(urlimagen, tipo);

    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    int dash = 500;
    int short_gap = 200;

    long[] pattern = { 0, // Start immediately
            dash, short_gap, dash, short_gap, dash };

    Intent notificationIntent;
    String ringtone;
    int ledlight;

    if (tipo.equalsIgnoreCase("Movie")) {
        ringtone = ringmovie;
        notificationIntent = new Intent(context, Peli.class);
        ledlight = preferencias.getInt("ledMovie", 0);

    } else {
        notificationIntent = new Intent(context, Tv.class);
        ringtone = ringtv;
        ledlight = preferencias.getInt("ledTV", 0);
        System.out.println(ledlight);
    }
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("passed", urlarticulo);

    PendingIntent pendingIntent;

    pendingIntent = PendingIntent.getActivity(context, randomInt, notificationIntent, 0);

    Notification myNotification;
    myNotification = new NotificationCompat.Builder(context).setPriority(1).setContentTitle(message)
            .setTicker(ticker).setLights(ledlight, 300, 300).setWhen(System.currentTimeMillis())
            .setContentIntent(pendingIntent).setSound(Uri.parse(ringtone)).setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_stat_ic_argenteam_gcm).build();

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        RemoteViews views;
        views = new RemoteViews(getPackageName(), R.layout.custom_notification);
        views.setImageViewBitmap(R.id.big_picture, bitmap);
        views.setImageViewBitmap(R.id.big_icon,
                BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_ic_argenteam_gcm));
        views.setTextViewText(R.id.title, message);
        myNotification.bigContentView = views;
    }

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if (movieoff && tipo.equalsIgnoreCase("Movie")) {
        if (vib) {
            v.vibrate(pattern, -1);
        }
        notificationManager.notify(randomInt, myNotification);

    }

    if (tvoff && tipo.equalsIgnoreCase("Serie TV")) {
        if (vib) {
            v.vibrate(pattern, -1);
        }
        notificationManager.notify(randomInt, myNotification);

    }

}