Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

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

Prototype

int FLAG_UPDATE_CURRENT

To view the source code for android.app PendingIntent FLAG_UPDATE_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Usage

From source file:com.cc.basefunction.service.MyFirebaseMessagingService.java

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 *//* ww w .  j  a v a2 s . co m*/
private void sendNotification(String messageBody) {
    Intent intentClick = new Intent(this, NotificationBroadCast.class);
    intentClick.setAction("BASEFUNCTION_NOTIFICATION_CLICK");
    intentClick.putExtra("message", messageBody);
    PendingIntent pendingIntentClick = PendingIntent.getBroadcast(this, 0, intentClick,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent intentCancel = new Intent(this, NotificationBroadCast.class);
    intentCancel.setAction("BASEFUNCTION_NOTIFICATION_CANCEL");
    intentCancel.putExtra("message", messageBody);
    PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, intentCancel,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notificationBuilder.setSmallIcon(R.drawable.notification_iocn);
        notificationBuilder.setColor(getResources().getColor(R.color.blue_B0E0E6));
    } else {
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
    }
    notificationBuilder.setContentTitle("BaseFunction Notification").setContentText(messageBody)
            .setSound(defaultSoundUri).setContentIntent(pendingIntentClick)
            .setDeleteIntent(pendingIntentCancel);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    notificationManager.notify(10086 /* ID of notification */, notificationBuilder.build());
}

From source file:com.sip.pwc.sipphone.service.Downloader.java

@Override
protected void onHandleIntent(Intent intent) {
    HttpGet getMethod = new HttpGet(intent.getData().toString());
    int result = Activity.RESULT_CANCELED;
    String outPath = intent.getStringExtra(EXTRA_OUTPATH);
    boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
    int icon = intent.getIntExtra(EXTRA_ICON, 0);
    String title = intent.getStringExtra(EXTRA_TITLE);
    boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));

    // Build notification
    Builder nb = new Builder(this);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentTitle(title);/*from w w  w . j  a  va 2 s.  c  o m*/
    nb.setSmallIcon(android.R.drawable.stat_sys_download);
    nb.setOngoing(true);
    Intent i = new Intent(this, SipHome.class);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));

    RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.download_notif);
    contentView.setImageViewResource(R.id.status_icon, icon);
    contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
    contentView.setProgressBar(R.id.status_progress, 50, 0, false);
    contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
    nb.setContent(contentView);

    final Notification notification = showNotif ? nb.build() : null;
    notification.contentView = contentView;
    if (!TextUtils.isEmpty(outPath)) {
        try {
            File output = new File(outPath);
            if (output.exists()) {
                output.delete();
            }

            if (notification != null) {
                notificationManager.notify(NOTIF_DOWNLOAD, notification);
            }
            ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
                private int oldState = 0;

                @Override
                public void run(long progress, long total) {
                    //Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
                    int newState = (int) Math.round(progress * 50.0f / total);
                    if (oldState != newState) {

                        notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
                        notificationManager.notify(NOTIF_DOWNLOAD, notification);
                        oldState = newState;
                    }

                }
            });
            boolean hasReply = client.execute(getMethod, responseHandler);

            if (hasReply) {

                if (checkMd5) {
                    URL url = new URL(intent.getData().toString().concat(".md5sum"));
                    InputStream content = (InputStream) url.getContent();
                    if (content != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(content));
                        String downloadedMD5 = "";
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            throw new IOException("md5_verification : no sum on server");
                        }
                        if (!MD5.checkMD5(downloadedMD5, output)) {
                            throw new IOException("md5_verification : incorrect");
                        }
                    }
                }
                PendingIntent pendingIntent = (PendingIntent) intent
                        .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + outPath);
                } catch (IOException e) {
                    Log.e(THIS_FILE, "Unable to make the apk file readable", e);
                }

                Log.d(THIS_FILE, "Download finished of : " + outPath);
                if (pendingIntent != null) {

                    notification.contentIntent = pendingIntent;
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.icon = android.R.drawable.stat_sys_download_done;
                    notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
                    notification.contentView.setTextViewText(R.id.status_text,
                            getResources().getString(R.string.done)
                                    // TODO should be a parameter of this class
                                    + " - Click to install");
                    notificationManager.notify(NOTIF_DOWNLOAD, notification);

                    /*
                    try {
                       pendingIntent.send();
                         notificationManager.cancel(NOTIF_DOWNLOAD);
                    } catch (CanceledException e) {
                       Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
                    }
                    */
                } else {
                    Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
                }

                result = Activity.RESULT_OK;
            }
        } catch (IOException e) {
            Log.e(THIS_FILE, "Exception in download", e);
        }
    }

    if (result == Activity.RESULT_CANCELED) {
        notificationManager.cancel(NOTIF_DOWNLOAD);
    }
}

From source file:com.sonetel.service.Downloader.java

@Override
protected void onHandleIntent(Intent intent) {
    HttpGet getMethod = new HttpGet(intent.getData().toString());
    int result = Activity.RESULT_CANCELED;
    String outPath = intent.getStringExtra(EXTRA_OUTPATH);
    boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
    int icon = intent.getIntExtra(EXTRA_ICON, 0);
    String title = intent.getStringExtra(EXTRA_TITLE);
    boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));

    // Build notification
    Builder nb = new NotificationCompat.Builder(this);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentTitle(title);/*from ww w  .  j  av  a  2  s .c  om*/
    nb.setSmallIcon(android.R.drawable.stat_sys_download);
    nb.setOngoing(true);
    Intent i = new Intent(this, SipHome.class);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));

    RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.download_notif);
    contentView.setImageViewResource(R.id.status_icon, icon);
    contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
    contentView.setProgressBar(R.id.status_progress, 50, 0, false);
    contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
    nb.setContent(contentView);

    final Notification notification = showNotif ? nb.getNotification() : null;
    notification.contentView = contentView;
    if (!TextUtils.isEmpty(outPath)) {
        try {
            File output = new File(outPath);
            if (output.exists()) {
                output.delete();
            }

            if (notification != null) {
                notificationManager.notify(NOTIF_DOWNLOAD, notification);
            }
            ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
                private int oldState = 0;

                @Override
                public void run(long progress, long total) {
                    //Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
                    int newState = (int) Math.round(progress * 50.0f / total);
                    if (oldState != newState) {

                        notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
                        notificationManager.notify(NOTIF_DOWNLOAD, notification);
                        oldState = newState;
                    }

                }
            });
            boolean hasReply = client.execute(getMethod, responseHandler);

            if (hasReply) {

                if (checkMd5) {
                    URL url = new URL(intent.getData().toString().concat(".md5sum"));
                    InputStream content = (InputStream) url.getContent();
                    if (content != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(content));
                        String downloadedMD5 = "";
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            throw new IOException("md5_verification : no sum on server");
                        }
                        if (!MD5.checkMD5(downloadedMD5, output)) {
                            throw new IOException("md5_verification : incorrect");
                        }
                    }
                }
                PendingIntent pendingIntent = (PendingIntent) intent
                        .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + outPath);
                } catch (IOException e) {
                    Log.e(THIS_FILE, "Unable to make the apk file readable", e);
                }

                Log.d(THIS_FILE, "Download finished of : " + outPath);
                if (pendingIntent != null) {

                    notification.contentIntent = pendingIntent;
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.icon = android.R.drawable.stat_sys_download_done;
                    notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
                    notification.contentView.setTextViewText(R.id.status_text,
                            getResources().getString(R.string.done)
                                    // TODO should be a parameter of this class
                                    + " - Click to install");
                    notificationManager.notify(NOTIF_DOWNLOAD, notification);

                    /*
                    try {
                       pendingIntent.send();
                         notificationManager.cancel(NOTIF_DOWNLOAD);
                    } catch (CanceledException e) {
                       Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
                    }
                    */
                } else {
                    Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
                }

                result = Activity.RESULT_OK;
            }
        } catch (IOException e) {
            Log.e(THIS_FILE, "Exception in download", e);
        }
    }

    if (result == Activity.RESULT_CANCELED) {
        notificationManager.cancel(NOTIF_DOWNLOAD);
    }
}

From source file:com.csipsimple.service.Downloader.java

@Override
protected void onHandleIntent(Intent intent) {
    HttpGet getMethod = new HttpGet(intent.getData().toString());
    int result = Activity.RESULT_CANCELED;
    String outPath = intent.getStringExtra(EXTRA_OUTPATH);
    boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
    int icon = intent.getIntExtra(EXTRA_ICON, 0);
    String title = intent.getStringExtra(EXTRA_TITLE);
    boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));

    // Build notification
    Builder nb = new NotificationCompat.Builder(this);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentTitle(title);//from  ww  w .j a  v  a  2  s. c  o m
    nb.setSmallIcon(android.R.drawable.stat_sys_download);
    nb.setOngoing(true);
    Intent i = new Intent(this, SipHome.class);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));

    RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.download_notif);
    contentView.setImageViewResource(R.id.status_icon, icon);
    contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
    contentView.setProgressBar(R.id.status_progress, 50, 0, false);
    contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
    nb.setContent(contentView);

    final Notification notification = showNotif ? nb.build() : null;
    notification.contentView = contentView;
    if (!TextUtils.isEmpty(outPath)) {
        try {
            File output = new File(outPath);
            if (output.exists()) {
                output.delete();
            }

            if (notification != null) {
                notificationManager.notify(NOTIF_DOWNLOAD, notification);
            }
            ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
                private int oldState = 0;

                @Override
                public void run(long progress, long total) {
                    //Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
                    int newState = (int) Math.round(progress * 50.0f / total);
                    if (oldState != newState) {

                        notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
                        notificationManager.notify(NOTIF_DOWNLOAD, notification);
                        oldState = newState;
                    }

                }
            });
            boolean hasReply = client.execute(getMethod, responseHandler);

            if (hasReply) {

                if (checkMd5) {
                    URL url = new URL(intent.getData().toString().concat(".md5sum"));
                    InputStream content = (InputStream) url.getContent();
                    if (content != null) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(content));
                        String downloadedMD5 = "";
                        try {
                            downloadedMD5 = br.readLine().split("  ")[0];
                        } catch (NullPointerException e) {
                            throw new IOException("md5_verification : no sum on server");
                        }
                        if (!MD5.checkMD5(downloadedMD5, output)) {
                            throw new IOException("md5_verification : incorrect");
                        }
                    }
                }
                PendingIntent pendingIntent = (PendingIntent) intent
                        .getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + outPath);
                } catch (IOException e) {
                    Log.e(THIS_FILE, "Unable to make the apk file readable", e);
                }

                Log.d(THIS_FILE, "Download finished of : " + outPath);
                if (pendingIntent != null) {

                    notification.contentIntent = pendingIntent;
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.icon = android.R.drawable.stat_sys_download_done;
                    notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
                    notification.contentView.setTextViewText(R.id.status_text,
                            getResources().getString(R.string.done)
                                    // TODO should be a parameter of this class
                                    + " - Click to install");
                    notificationManager.notify(NOTIF_DOWNLOAD, notification);

                    /*
                    try {
                       pendingIntent.send();
                         notificationManager.cancel(NOTIF_DOWNLOAD);
                    } catch (CanceledException e) {
                       Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
                    }
                    */
                } else {
                    Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
                }

                result = Activity.RESULT_OK;
            }
        } catch (IOException e) {
            Log.e(THIS_FILE, "Exception in download", e);
        }
    }

    if (result == Activity.RESULT_CANCELED) {
        notificationManager.cancel(NOTIF_DOWNLOAD);
    }
}

From source file:com.chess.genesis.net.GenesisNotifier.java

private static void CancelWakup(final Context context) {
    final Intent intent = new Intent(context, GenesisAlarm.class);
    final PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pintent);//from w ww.  j  a va  2s.  c om
}

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

@Override
public void onCreate() {
    settings = new AppSettings(this);
    mDb = new ScrobblesDatabase(this);
    mDb.open();/*  w ww .j a va  2s .  c  o  m*/
    mNetManager = new NetworkerManager(this, mDb);

    int sdk = Build.VERSION.SDK_INT;
    if (sdk == Build.VERSION_CODES.GINGERBREAD || sdk == Build.VERSION_CODES.GINGERBREAD_MR1) {

        String ar = "";
        String tr = "";
        String api = "";
        if (mCurrentTrack != null) {
            ar = mCurrentTrack.getArtist();
            tr = mCurrentTrack.getTrack();
            api = mCurrentTrack.getMusicAPI().readAPIname();
        }

        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(ar)
                .setSmallIcon(R.mipmap.ic_notify).setContentText(tr + " : " + api)
                .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);
            this.startService(iNoti);
        }
    }
}

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

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

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

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

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

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

                            builder.setVibrate(VIBRATION_PATTERN);

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

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

}

From source file:damo.three.ie.prepay.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    try {/*from w w w. ja v a2 s .  co  m*/
        Log.d(Constants.TAG, "Fetching usages from service.");
        UsageFetcher usageFetcher = new UsageFetcher(context, true);
        JSONArray usages = usageFetcher.getUsages();

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences sharedUsagePref = context.getSharedPreferences("damo.three.ie.previous_usage",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedUsagePref.edit();
        editor.putLong("last_refreshed_milliseconds", new DateTime().getMillis());
        editor.putString("usage_info", usages.toString());
        editor.commit();

        // Register alarms for newly refreshed usages in background
        boolean notificationsEnabled = sharedPref.getBoolean("notification", true);
        List<UsageItem> usageItems = JSONUtils.jsonToUsageItems(usages);
        List<BasicUsageItem> basicUsageItems = UsageUtils.getAllBasicItems(usageItems);
        UsageUtils.registerInternetExpireAlarm(context, basicUsageItems, notificationsEnabled, true);

    } catch (Exception e) {
        // Try again at 7pm, unless its past 7pm. Then forget and let tomorrow's alarm do the updating.
        // Still trying to decide if I need a more robust retry mechanism.
        Log.d(Constants.TAG, "Caught exception: " + e.getLocalizedMessage());
        Calendar calendar = Calendar.getInstance();
        if (calendar.get(Calendar.HOUR_OF_DAY) < Constants.HOUR_TO_RETRY) {
            Log.d(Constants.TAG, "Scheduling a re-try for 7pm");
            calendar.set(Calendar.HOUR_OF_DAY, Constants.HOUR_TO_RETRY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            Intent receiver = new Intent(context, UpdateReceiver.class);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // Using different request code to 0 so it won't conflict with other alarm below.
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 3, receiver,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Keeping efficiency in mind:
            // http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME
            am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
        }
    } finally {
        Log.d(Constants.TAG, "Finish UpdateService");
        UpdateReceiver.completeWakefulIntent(intent);
    }
}

From source file:alaindc.crowdroid.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *//*  w  w w  .j  av  a  2s  . co  m*/
private void sendNotification(String nameofsensor) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.drawable.icon)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)).setColor(Color.RED)
            .setContentTitle("Geofence Crowdroid").setContentText("Geofence Trigger: " + nameofsensor)
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:com.example.mobileid.GcmIntentService.java

private void sendNotification(Intent intent) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Bundle extras = intent.getExtras();// w w w . j  a  v  a  2 s .c om
    JSONObject gcmObj;
    try {
        gcmObj = new JSONObject(extras.getString("message"));
        String msg = gcmObj.getString("info");

        Intent passIntent = new Intent();
        passIntent.setClass(this, MainActivity.class);
        passIntent.putExtra("gcmMsg", gcmObj.toString());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, passIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        if (msg.compareToIgnoreCase("websign") != 0) {
            //              NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            mBuilder.setSmallIcon(R.drawable.ic_launcher).setContentTitle("mobileID")
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
        } else {
            //            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            mBuilder.setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("Web Sign - " + gcmObj.getString("title"))
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                    .setContentText(gcmObj.getString("content"));
        }

        //default notification sound
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);

        //cleared after clicking
        mBuilder.setAutoCancel(true);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    } catch (Exception e) {
        e.printStackTrace();
    }
}