Example usage for android.app NotificationManager notify

List of usage examples for android.app NotificationManager notify

Introduction

In this page you can find the example usage for android.app NotificationManager notify.

Prototype

public void notify(int id, Notification notification) 

Source Link

Document

Post a notification to be shown in the status bar.

Usage

From source file:com.android.example.leanback.fastlane.RecommendationsService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentProviderClient client = getContentResolver()
            .acquireContentProviderClient(VideoItemContract.VideoItem.buildDirUri());
    try {/*from  w w  w. ja v a 2s  . c o m*/
        Cursor cursor = client.query(VideoItemContract.VideoItem.buildDirUri(), VideoDataManager.PROJECTION,
                null, null, VideoItemContract.VideoItem.DEFAULT_SORT);

        VideoDataManager.VideoItemMapper mapper = new VideoDataManager.VideoItemMapper();
        mapper.bindColumns(cursor);

        NotificationManager mNotificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Log.d(TAG, mNotificationManager == null ? "It's null" : mNotificationManager.toString());

        int count = 1;

        while (cursor.moveToNext() && count <= MAX_RECOMMENDATIONS) {

            Video video = mapper.bind(cursor);
            PendingIntent pendingIntent = buildPendingIntent(video);
            Bundle extras = new Bundle();
            extras.putString(EXTRA_BACKGROUND_IMAGE_URL, video.getThumbUrl());

            Bitmap image = Picasso.with(getApplicationContext()).load(video.getThumbUrl())
                    .resize(VideoDetailsFragment.dpToPx(DETAIL_THUMB_WIDTH, getApplicationContext()),
                            VideoDetailsFragment.dpToPx(DETAIL_THUMB_HEIGHT, getApplicationContext()))
                    .get();

            Notification notification = new NotificationCompat.BigPictureStyle(
                    new NotificationCompat.Builder(getApplicationContext()).setContentTitle(video.getTitle())
                            .setContentText(video.getDescription()).setPriority(4).setLocalOnly(true)
                            .setOngoing(true)
                            .setColor(getApplicationContext().getResources().getColor(R.color.primary))
                            // .setCategory(Notification.CATEGORY_RECOMMENDATION)
                            .setCategory("recommendation").setLargeIcon(image)
                            .setSmallIcon(R.drawable.ic_stat_f).setContentIntent(pendingIntent)
                            .setExtras(extras)).build();

            mNotificationManager.notify(count, notification);
            count++;
        }

        cursor.close();
    } catch (RemoteException re) {
        Log.e(TAG, "Cannot query VideoItems", re);
    } catch (IOException re) {
        Log.e(TAG, "Cannot download thumbnail", re);
    } finally {
        client.release();
    }
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private boolean processRestrictions(Restrictions currRestr, Restrictions newRestr, Account account)
        throws OperationApplicationException {
    boolean resync = false;
    if (newRestr != null && (currRestr == null || !currRestr.equals(newRestr))) {
        // Notify User.
        NotificationManager notificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        if (currRestr != null && newRestr.isPhotoSyncSupported() && !currRestr.isPhotoSyncSupported()) {

            // Create ViewAccount-Intent
            Intent viewAccountsIntent = new Intent(mContext, ViewAccountsActivity.class);
            // Adds the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(ViewAccountsActivity.class);
            stackBuilder.addNextIntent(viewAccountsIntent);

            // Photo sync possible.
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(Constants.NOTIF_ICON)
                    .setContentTitle(mContext.getText(R.string.notif_photosyncenabled_title).toString())
                    .setContentText(account.name).setAutoCancel(true).setOnlyAlertOnce(true)
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
            notificationManager.notify(Constants.NOTIF_PHOTO_SYNC_SUPPORTED, mBuilder.build());
            // Resync to sync Photos
            resync = true;//from w  w w  .  jav  a2 s .  c  o  m

            setExplicitSavePhoto(account, true);
        }
        if (newRestr.isPhotoSyncSupported()) {
            notificationManager.cancel(Constants.NOTIF_PHOTO_NOT_SYNCED);
        }
        if (!newRestr.isPhotoSyncSupported()) {
            notificationManager.cancel(Constants.NOTIF_PHOTO_SYNC_SUPPORTED);
        }

        if (currRestr != null && newRestr.getMaxContactCount() != currRestr.getMaxContactCount()) {
            // Create ViewAccount-Intent
            Intent viewAccountsIntent = new Intent(mContext, ViewAccountsActivity.class);
            // Adds the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(ViewAccountsActivity.class);
            stackBuilder.addNextIntent(viewAccountsIntent);
            boolean moreAllowed = newRestr.getMaxContactCount() > currRestr.getMaxContactCount();
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(Constants.NOTIF_ICON)
                    .setContentTitle(moreAllowed ? getText(R.string.notif_contact_moresupported_title)
                            : getText(R.string.notif_contact_lesssupported_title))
                    .setContentText(String.format(getText(R.string.notif_contact_supported_content),
                            newRestr.getMaxContactCount(), account.name))
                    .setAutoCancel(true).setOnlyAlertOnce(true)
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
            notificationManager.notify(Constants.NOTIF_MAX_CONTACT_SUPPORTED, mBuilder.build());
            // Hide Contacts not syned, but allow the message to show up
            // again if there are still more than allowed.
            notificationManager.cancel(Constants.NOTIF_CONTACTS_NOT_SYNCED);
            unhideMaxContactMessage(mContext, account);
        }

        if (resync) {
            ContactManager.setDirtyFlag(mContext, account);
        }

        SyncUtils.saveRestrictions(account, mAccountManager, newRestr);
    }
    return resync;
}

From source file:com.intel.xdk.notification.Notification.java

public void showBusyIndicator() {
    if (spinner != null)
        return;//w  ww  .j a v a  2s.  c  om

    //get a reference to the service
    String ns = Context.NOTIFICATION_SERVICE;
    final NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(ns);
    //create the notification instance
    int icon = activity.getResources().getIdentifier("spinner_n", "drawable", activity.getPackageName());//R.drawable.spinner_n;

    PackageManager packageManager = activity.getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(activity.getPackageName(), 0);
    } catch (final NameNotFoundException e) {
    }
    final String title = (String) ((applicationInfo != null)
            ? packageManager.getApplicationLabel(applicationInfo)
            : "???");

    CharSequence tickerText = title + " is busy...";//activity.getString(R.string.app_name) + " is busy...";
    long when = System.currentTimeMillis();
    final android.app.Notification notification = new android.app.Notification(icon, tickerText, when);
    //initialize latest event info
    Context context = activity.getApplicationContext();
    CharSequence contentTitle = title + " is busy...";//activity.getString(R.string.app_name) + " is busy...";
    CharSequence contentText = "...just a moment please.";
    Intent notificationIntent = new Intent(activity, activity.getClass());
    PendingIntent contentIntent = PendingIntent.getActivity(activity, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    //make notification non-cancellable
    notification.flags = notification.flags | android.app.Notification.FLAG_NO_CLEAR;
    //show in status bar
    mNotificationManager.notify(BUSY_INDICATOR, notification);
    //animate the icon
    spinner = new Thread("intel.xdk.notification:showBusyIndicator") {
        public void run() {
            //frame pointer
            int currentFrame = 0;
            //frame array
            //int[] frames = new int[]{R.drawable.spinner_ne, R.drawable.spinner_e, R.drawable.spinner_se, R.drawable.spinner_s, R.drawable.spinner_sw, R.drawable.spinner_w, R.drawable.spinner_nw, R.drawable.spinner_n};
            int[] frames = new int[] {
                    activity.getResources().getIdentifier("spinner_ne", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_e", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_se", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_s", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_sw", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_w", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_nw", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_n", "drawable", activity.getPackageName()) };
            Thread thisThread = Thread.currentThread();
            while (spinner == thisThread) {
                //loop over the frames, updating the icon every 200 ms
                currentFrame++;
                currentFrame %= frames.length;
                notification.icon = frames[currentFrame];
                mNotificationManager.notify(BUSY_INDICATOR, notification);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //when looping ends, remove notification from status bar
            mNotificationManager.cancel(BUSY_INDICATOR);
        }

        @Override
        protected void finalize() throws Throwable {
            //in case the process crashes, try to remove notification from status bar
            super.finalize();
            mNotificationManager.cancel(BUSY_INDICATOR);
        }
    };
    spinner.start();
}

From source file:de.kollode.redminebrowser.sync.SyncHelper.java

void performSync(SyncResult syncResult, Account account) throws IOException {

    NotificationManager mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    android.support.v4.app.NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setContentTitle("Projects").setContentText("Syncing in progress")
            .setSmallIcon(R.drawable.ic_launcher);

    final ContentResolver resolver = mContext.getContentResolver();
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    AccountManager accMgr = AccountManager.get(this.mContext);
    String serverUrl = accMgr.getUserData(account, "serverUrl");

    if (isOnline()) {

        final long startRemote = System.currentTimeMillis();

        int syncedProjects = 0;
        Log.i(sTag, "Remote syncing speakers");
        Log.i(sTag, serverUrl);//from w ww  .  j  ava2s.  c o m

        try {

            int offset = 0;
            int numberOfProjects;
            int limit = 100;
            boolean loadMore = true;

            do {
                String restQuery = "sort=updated_on:desc&limit=" + limit + "&offset=" + offset + "&key="
                        + accMgr.getPassword(account);

                Log.d(sTag, "REST URL: " + serverUrl + "/projects.json?" + restQuery);
                JSONObject projectsJson = getJsonFromUrl(serverUrl + "/projects.json?" + restQuery);

                numberOfProjects = projectsJson.getInt("total_count");
                mBuilder.setProgress(numberOfProjects, syncedProjects, false);
                mNotificationManager.notify(0, mBuilder.build());

                if (numberOfProjects < limit + offset) {
                    Log.d(sTag, "Enough Projects");
                    loadMore = false;
                } else {
                    Log.d(sTag, "More Projects");
                    offset += limit;
                }

                JSONArray projects = projectsJson.getJSONArray("projects");

                for (int i = 0; i < projects.length(); i++) {

                    JSONObject project = projects.getJSONObject(i);
                    Builder projectBuilder = ContentProviderOperation
                            .newInsert(Project.buildProjectsUri(account.name));

                    Log.d(sTag, project.toString());

                    try {
                        projectBuilder.withValue(Project.PARENT, project.getJSONObject("parent").getInt("id"));
                    } catch (Exception e) {

                    }

                    batch.add(projectBuilder.withValue(BaseColumns._ID, project.getInt("id"))
                            .withValue(Project.NAME, project.getString("name"))
                            .withValue(Project.IDENTIFIER, project.getString("identifier"))
                            .withValue(Project.UPDATED, System.currentTimeMillis())
                            .withValue(Project.CREATED, System.currentTimeMillis())
                            .withValue(Project.CREATED_ON, project.getString("created_on"))
                            .withValue(Project.UPDATED_ON, project.getString("updated_on")).build());

                    mBuilder.setProgress(numberOfProjects, syncedProjects++, false);
                    mNotificationManager.notify(0, mBuilder.build());
                }
            } while (loadMore && !this.isCanceled());

            try {
                // Apply all queued up batch operations for local data.
                resolver.applyBatch(RedmineTables.CONTENT_AUTHORITY, batch);
            } catch (RemoteException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            } catch (OperationApplicationException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            }

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

        if (this.isCanceled()) {
            mBuilder.setContentText("Sync was canceled").setProgress(0, 0, false);
        } else {
            mBuilder.setContentText("Sync complete").setProgress(0, 0, false);
        }
        mNotificationManager.notify(0, mBuilder.build());

        syncResult.delayUntil = ((long) 60 * 60);

        Log.d(sTag, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
        Log.d(sTag, "Number of projects: " + syncedProjects);
    }
}

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

private void generateNotification(final String title, final String body, final int count) {
    mHandler.post(new Runnable() {
        public void run() {
            // Get app icon bitmap and scale to fit in notification
            Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            largeIcon = Bitmap.createScaledBitmap(largeIcon, NOTIFICATION_IMAGE_SIZE, NOTIFICATION_IMAGE_SIZE,
                    true);/*w  w  w. j  av  a  2s.  c o m*/

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
                    .setLargeIcon(largeIcon).setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
                    .setContentText(body);

            // Creates an explicit intent for an Activity in your app
            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);

            // The stack builder object will contain an artificial back stack for the
            // started Activity.
            // This ensures that navigating backward from the Activity leads out of
            // your application to the Home screen.
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
            // Adds the back stack for the Intent (but not the Intent itself)
            stackBuilder.addParentStack(MainActivity.class);
            // Adds the Intent that starts the Activity to the top of the stack
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setNumber(count);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);

            // Play default notification sound
            mBuilder.setDefaults(Notification.DEFAULT_SOUND);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(0, mBuilder.build());
        }
    });
}

From source file:chron.carlosrafael.chatapp.MyFirebaseMessagingService.java

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 *///  w  w  w . j a va 2s.  c om
private void sendNotification(String messageBody, String messageUser) {

    //Se ainda nao tiver clicado na notification a ID vai ter que ser a mesma
    //Se tiver clicado entao temos que gerar uma nova ID
    int notificationID;
    if (NotificationHandler.createNewNotification) {
        Random generator = new Random();
        notificationID = generator.nextInt(100);

        NotificationHandler.onGoingNotificationID = notificationID;

        //Dizendo que nao precisa criar uma nova notificacao ate o usuario clicar na notificacao e abrir o chat
        NotificationHandler.createNewNotification = false;
    } else {
        notificationID = NotificationHandler.onGoingNotificationID;
    }

    //Quando o usuario clicar ele vai pra o MainActivity
    Intent intent = new Intent(this, HomeActivity.class);

    //Botando um Extra para quando ele abrir por um Intent vindo do notification ele para de acumular as
    //mensagens de notificacao
    intent.putExtra("fromNotification", true);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("New message in chat")
            .setContentText(messageUser + " : " + messageBody).setAutoCancel(true).setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    //Adicionando as mensagens no ArrayList que mantem todas as mensagens da notification que ainda vai ser vista
    NotificationHandler.notificationMessages.add(messageUser + " : " + messageBody);

    //Se nao eh pra criar uma nova notificacao entao temos que:
    // 1 - Adicionar essa mensagem como a ultima no ArrayList da notificacao
    // 2 - Ler o ArrayList pra criar o InboxStyle com todas as mensagens
    if (!NotificationHandler.createNewNotification) {

        int numMessages = NotificationHandler.notificationMessages.size();

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String title = (numMessages > 1) ? String.valueOf(numMessages) + " new messages in chat"
                : String.valueOf(numMessages) + " new message in chat";
        inboxStyle.setBigContentTitle(title);
        //inboxStyle.addLine(messageBody);
        for (int i = 0; i < NotificationHandler.notificationMessages.size(); i++) {
            //notificationBuilder.setContentText("Tamo no loop" + String.valueOf(i))
            notificationBuilder.setNumber(NotificationHandler.notificationMessages.size());
            inboxStyle.addLine(NotificationHandler.notificationMessages.get(i));
            //inboxStyle.addLine("Tamo no loop" + String.valueOf(i));
            // Because the ID remains unchanged, the existing notification is
            // updated.
            //            notificationManager.notify(
            //                    notificationID,
            //                    notificationBuilder.build());
        }

        notificationBuilder.setStyle(inboxStyle);
    }

    notificationManager.notify(notificationID, notificationBuilder.build());

    // Issue the notification here.

    //notificationManager.notify(notificationID /* ID of notification */, notificationBuilder.build());

}

From source file:androidVNC.VncCanvasActivity.java

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    database = new VncDatabase(this);
    connection = new ConnectionBean();

    Intent i = getIntent();//  w w w  .java  2s .c o  m
    Uri data = i.getData();
    if ((data != null) && (data.getScheme().equals("vnc"))) {
        String host = data.getHost();
        // This should not happen according to Uri contract, but bug introduced in Froyo (2.2)
        // has made this parsing of host necessary
        int index = host.indexOf(':');
        int port;
        if (index != -1) {
            try {
                port = Integer.parseInt(host.substring(index + 1));
            } catch (NumberFormatException nfe) {
                port = 0;
            }
            host = host.substring(0, index);
        } else {
            port = data.getPort();
        }
        if (host.equals(VncConstants.CONNECTION)) {
            if (connection.Gen_read(database.getReadableDatabase(), port)) {
                MostRecentBean bean = androidVNC.getMostRecent(database.getReadableDatabase());
                if (bean != null) {
                    bean.setConnectionId(connection.get_Id());
                    bean.Gen_update(database.getWritableDatabase());
                }
            }
        } else {
            connection.setAddress(host);
            connection.setNickname(connection.getAddress());
            connection.setPort(port);
            List<String> path = data.getPathSegments();
            if (path.size() >= 1) {
                connection.setColorModel(path.get(0));
            }
            if (path.size() >= 2) {
                connection.setPassword(path.get(1));
            }
            connection.save(database.getWritableDatabase());
        }
    } else {

        Bundle extras = i.getExtras();

        if (extras != null) {
            connection.Gen_populate((ContentValues) extras.getParcelable(VncConstants.CONNECTION));
        }
        if (connection.getPort() == 0)
            connection.setPort(5900);

        // Parse a HOST:PORT entry
        String host = connection.getAddress();
        if (host.indexOf(':') > -1) {
            String p = host.substring(host.indexOf(':') + 1);
            try {
                connection.setPort(Integer.parseInt(p));
            } catch (Exception e) {
            }
            connection.setAddress(host.substring(0, host.indexOf(':')));
        }
    }

    try {
        setContentView(fi.aalto.openoranges.project1.mcc.R.layout.canvas);
        vncCanvas = (VncCanvas) findViewById(fi.aalto.openoranges.project1.mcc.R.id.vnc_canvas);
        zoomer = (ZoomControls) findViewById(R.id.zoomer);
    } catch (Exception e) {
        e.printStackTrace();
    }

    vncCanvas.initializeVncCanvas(connection, new Runnable() {
        public void run() {
            setModes();
        }
    });
    vncCanvas.setOnGenericMotionListener(this);
    zoomer.hide();

    zoomer.setOnZoomInClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            showZoomer(true);
            vncCanvas.scaling.zoomIn(VncCanvasActivity.this);

        }

    });
    zoomer.setOnZoomOutClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            showZoomer(true);
            vncCanvas.scaling.zoomOut(VncCanvasActivity.this);

        }

    });
    zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMgr.toggleSoftInput(0, 0);
        }

    });

    panner = new Panner(this, vncCanvas.handler);
    inputHandler = getInputHandlerById(fi.aalto.openoranges.project1.mcc.R.id.itemInputFitToScreen);

    mToken = getIntent().getStringExtra("token");
    mId = getIntent().getStringExtra("id");
    mName = getIntent().getStringExtra("name");

    //listener for the back-button
    registerClickCallback();

    //Notification in status bar
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(VncCanvasActivity.this)
            .setSmallIcon(R.drawable.icon_white).setContentTitle(mName + " running")
            .setContentText("Click to open the application screen");

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(VncCanvasActivity.this, VncCanvasActivity.class);
    resultIntent.setAction(Long.toString(System.currentTimeMillis()));
    mBuilder.setContentIntent(PendingIntent.getActivity(VncCanvasActivity.this, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mNotifyID allows you to update the notification later on.
    mNotificationManager.notify(mNotifyId, mBuilder.build());
    startService();
}

From source file:com.actionbarsherlock.sample.hcgallery.MainActivity.java

void showNotification(boolean custom) {
    final Resources res = getResources();
    final NotificationManager notificationManager = (NotificationManager) getSystemService(
            NOTIFICATION_SERVICE);//w w  w .  ja va2s .c  om

    Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notify_example).setAutoCancel(true)
            .setTicker(getString(R.string.notification_text))
            .setContentIntent(getDialogPendingIntent("Tapped the notification entry."));

    if (custom) {
        // Sets a custom content view for the notification, including an image button.
        RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
        layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
        layout.setOnClickPendingIntent(R.id.notification_button,
                getDialogPendingIntent("Tapped the 'dialog' button in the notification."));
        builder.setContent(layout);

        // Notifications in Android 3.0 now have a standard mechanism for displaying large
        // bitmaps such as contact avatars. Here, we load an example image and resize it to the
        // appropriate size for large bitmaps in notifications.
        Bitmap largeIconTemp = BitmapFactory.decodeResource(res, R.drawable.notification_default_largeicon);
        Bitmap largeIcon = Bitmap.createScaledBitmap(largeIconTemp,
                res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
                res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false);
        largeIconTemp.recycle();

        builder.setLargeIcon(largeIcon);

    } else {
        builder.setNumber(7) // An example number.
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text));
    }

    notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

private void updateEnforcingNotification(int allowed, int total) {
    // Update notification
    Notification notification = getEnforcingNotification(allowed, total - allowed, mapHostsBlocked.size());
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.notify(NOTIFY_ENFORCING, notification);
}

From source file:kr.co.bettersoft.checkmileage.activities.GCMIntentService.java

/**
 * generateNotification// ww  w . ja  va2 s  . c  o  m
 * Issues a notification to inform the user that server has sent a message.
 * @param context
 * @param message
 * @return
 */
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when); // sdf
    String title = context.getString(R.string.app_name);
    String mileageUpdateStr = context.getString(R.string.mileage_noti);
    Intent notificationIntent;
    /*
     * MILEAGE :  ? ??  ? ???.
     * MARKETING : ?? ?    ?.
     * Check Mileage     ?. : test ..
     * 
     * <string name="gcm_new_msgkkk"> </string>
     */
    String new_msg = " ";

    if (message.equals(new_msg)) {
        Log.d(TAG, "new msg - test");
        notificationIntent = new Intent(context, DummyActivity.class);
        //            notificationIntent.putExtra("RunMode", "TEST");                  // ?? ? . ?? .. ?   ..
        notificationIntent.putExtra("RunMode", "MILEAGE"); //

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | 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;
        notificationManager.notify(0, notification);

        //        }else if(message.contains("MILEAGE")){
        //        }else if(message.contains(mileageUpdateStr)){         // ?? ?. ()
    } else if (message.equals(mileageUpdateStr)) { // ?? ?. ().
        Log.d(TAG, "update mileage");
        MyMileagePageActivity.searched = false;
        //           notificationIntent = new Intent(context, MainActivity.class);      // ? ?  ?..
        notificationIntent = new Intent(context, DummyActivity.class);
        notificationIntent.putExtra("RunMode", "MILEAGE");

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | 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;
        notificationManager.notify(0, notification);
    } else if (message.equals("MARKETING")) {
        Log.d(TAG, "noti event push");
        //           notificationIntent = new Intent(context, MainActivity.class);      // ? ?  ? ?  ..
        notificationIntent = new Intent(context, DummyActivity.class);
        notificationIntent.putExtra("RunMode", "MARKETING");
        notificationIntent.putExtra("MESSAGE", "New Event");
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | 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;
        notificationManager.notify(0, notification);
    } else { //  ?.
        Log.d(TAG, "noti event push");
        //           notificationIntent = new Intent(context, MainActivity.class);      // ? ?  ? ?  ..
        notificationIntent = new Intent(context, DummyActivity.class);
        notificationIntent.putExtra("RunMode", "MARKETING");
        notificationIntent.putExtra("MESSAGE", message);

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | 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;
        notificationManager.notify(0, notification);
    }
}