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:de.yaacc.upnp.server.YaaccUpnpServerService.java

/**
 * Displays the notification.//from ww  w.j  a v a 2s.  com
 */
private void showNotification() {
    Intent notificationIntent = new Intent(this, YaaccUpnpServerControlActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Yaacc Upnp Server")
            .setContentText(preferences
                    .getString(getApplicationContext().getString(R.string.settings_local_server_name_key), ""));
    mBuilder.setContentIntent(contentIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(NotificationId.UPNP_SERVER.getId(), mBuilder.build());
}

From source file:anastasoft.rallyvision.activity.MenuPrincipal.java

private void createNotification() {

    Intent resultIntent = new Intent(this, MenuPrincipal.class);

    // Because clicking the notification opens a new ("special") activity, there's
    // no need to create an artificial back stack.
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notify).setContentTitle(getString(R.string.notification_title))
            .setContentText(getString(R.string.notification_text)).setContentInfo(getString(R.string.app_name))
            .setAutoCancel(true).setOngoing(true).setTicker(getString(R.string.notification_ticker));

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to setState the notification later on.
    Notification notification = mBuilder.build();

    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

From source file:pj.rozkladWKD.C2DMReceiver.java

public void showNotification(String ticker, String contentTitle, String contentText, PendingIntent intent,
        int number) {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

    int icon = R.drawable.ic_launcher_wkd;
    CharSequence tickerText = ticker;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);
    Context context = getApplicationContext();
    notification.number = Prefs.getNotificationMessageNextNumber(context);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    SharedPreferences prefs = Prefs.get(context);
    if (prefs.getBoolean(Prefs.NOTIFICATION_SOUND, true))
        notification.defaults |= Notification.DEFAULT_SOUND;
    if (prefs.getBoolean(Prefs.NOTIFICATION_VIBRATION, true))
        notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    notification.setLatestEventInfo(context, contentTitle, contentText, intent);

    mNotificationManager.notify(NOTIFICATION_ID, notification);

}

From source file:de.wikilab.android.friendica01.FileUploadService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.i("Andfrnd/UploadFile", "onHandleIntent exec");

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

    //Instantiate the Notification:
    CharSequence tickerText = "Uploading...";
    Notification notification = new Notification(R.drawable.arrow_up, tickerText, System.currentTimeMillis());
    notification.flags |= Notification.FLAG_ONGOING_EVENT;

    //Define the Notification's expanded message and Intent:
    Context context = getApplicationContext();
    PendingIntent nullIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    notification.setLatestEventInfo(context, "Upload in progress...", "You are notified here when it completes",
            nullIntent);/*from  w ww .j  a  v a 2 s  . com*/

    //Pass the Notification to the NotificationManager:
    mNotificationManager.notify(UPLOAD_PROGRESS_ID, notification);
    /*
    final TwLogin login = new TwLogin();
    login.initialize(FileUploadService.this);
    login.doLogin(FileUploadService.this, null, false);
            
    if (!login.isLoginOK()) {
       showFailMsg(FileUploadService.this, "Invalid login data or no network connection");
       return;
    }
    */
    Bundle intentPara = intent.getExtras();
    fileToUpload = (Uri) intentPara.getParcelable(Intent.EXTRA_STREAM);
    descText = intentPara.getString(EXTRA_DESCTEXT);
    subject = intentPara.getString(Intent.EXTRA_SUBJECT);

    if (targetFilename == null || targetFilename.equals(""))
        targetFilename = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".txt";

    String fileSpec = Max.getRealPathFromURI(FileUploadService.this, fileToUpload);

    String tempFile = Max.IMG_CACHE_DIR + "/imgUploadTemp_" + System.currentTimeMillis() + ".jpg";
    Max.resizeImage(fileSpec, tempFile, 1024, 768);

    try {
        Log.i("Andfrnd/UploadFile", "before uploadFile");
        final TwAjax uploader = new TwAjax(FileUploadService.this, true, true);
        uploader.addPostFile(new TwAjax.PostFile("media", targetFilename, tempFile));
        uploader.addPostData("status", descText);
        uploader.addPostData("title", subject);
        uploader.addPostData("source",
                "<a href='http://friendica-for-android.wiki-lab.net'>Friendica for Android</a>");
        uploader.uploadFile(Max.getServer(this) + "/api/statuses/update", null);
        Log.i("Andfrnd/UploadFile", "after uploadFile");
        Log.i("Andfrnd/UploadFile", "isSuccess() = " + uploader.isSuccess());
        Log.i("Andfrnd/UploadFile", "getError() = " + uploader.getError());

        mNotificationManager.cancel(UPLOAD_PROGRESS_ID);
        if (uploader.isSuccess() && uploader.getError() == null) {
            JSONObject result = null;
            try {
                Log.i("Andfrnd/UploadFile", "JSON RESULT: " + uploader.getHttpCode());
                result = (JSONObject) uploader.getJsonResult();

                String postedText = result.getString("text");
                showSuccessMsg(FileUploadService.this);

            } catch (Exception e) {
                String errMes = e.getMessage() + " | " + uploader.getResult();
                if (result != null)
                    try {
                        errMes = result.getString("error");
                    } catch (JSONException fuuuuJava) {
                    }

                showFailMsg(FileUploadService.this, errMes);

                e.printStackTrace();
            }
        } else if (uploader.getError() != null) {
            showFailMsg(FileUploadService.this, uploader.getError().toString());
        } else {
            showFailMsg(FileUploadService.this, uploader.getResult());
        }

    } finally {
        new File(tempFile).delete();
    }
}

From source file:org.sigimera.app.android.GCMIntentService.java

@Override
protected final void onMessage(final Context context, final Intent message) {
    final Intent msg = message;
    this.mainThreadHandler.post(new Runnable() {
        public void run() {
            ApplicationController controller = ApplicationController.getInstance();
            controller.init(getApplicationContext(), getSharedPreferences(Constants.PREFS_NAME, 0), null);
            String authToken = controller.getSharedPreferences().getString("auth_token", null);
            final String type = msg.getStringExtra("sig_message_type");
            if (type.equalsIgnoreCase("NEW_CRISIS")) {
                /**/*from w  w  w  . j  a  v  a2s.co  m*/
                 * XXX: Blocks UI: Shift this code into a separate
                 * background thread
                 */
                Crisis crisis = PersistanceController.getInstance().getCrisis(authToken,
                        msg.getStringExtra("crisis_id"));

                StringBuffer message = new StringBuffer();
                if (crisis != null) {
                    message.append(crisis.getID());
                    message.append(" was stored successfully!");
                } else {
                    message.append("Not able to get crisis!");
                }
                Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show();
            } else if (type.equalsIgnoreCase("PING")) {
                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

                Intent notificationIntent = new Intent();
                PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                        notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

                Notification notification = new NotificationCompat.Builder(getApplicationContext())
                        .setContentTitle("Sigimera PING!")
                        .setContentText("Congratulations, push notifcation received!")
                        .setSmallIcon(R.drawable.sigimera_logo).setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_ALL).setContentIntent(contentIntent).build();

                mNotificationManager.notify(Constants.PING_ID, notification);
            } else if (type.equalsIgnoreCase("CRISIS_ALERT")) {
                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

                /**
                 * XXX: Not working with random ID. That makes always the
                 * latest notification clickable, but not the older ones.
                 */
                int notificationID = new Random().nextInt();
                Intent notificationIntent = new Intent(getApplicationContext(), CrisisAlertActivity.class);
                notificationIntent.putExtra("notification_id", notificationID);
                notificationIntent.putExtra("crisis_id", msg.getStringExtra("crisis_id"));
                notificationIntent.putExtra("crisis_type", msg.getStringExtra("crisis_type"));
                PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                        notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

                Notification notification = new NotificationCompat.Builder(getApplicationContext())
                        .setContentTitle("CRISIS ALERT!")
                        .setContentText("Crisis found: " + msg.getStringExtra("crisis_id"))
                        .setSmallIcon(R.drawable.alert_red).setOngoing(true).setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_ALL).setContentIntent(contentIntent).build();

                mNotificationManager.notify(notificationID, notification);
            } else if (type.equalsIgnoreCase("SHARED_CRISIS")) {
                Intent intent = new Intent(GCMIntentService.this, CrisisActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(Constants.CRISIS_ID, msg.getStringExtra("crisis_id"));
                intent.putExtra(Constants.WINDOW_TYPE, Constants.WINDOW_TYPE_SHARED_CRISIS);
                startActivity(intent);
            } else if (type.equalsIgnoreCase("UNREGISTER_DEVICE")) {
                GCMRegistrar.unregister(ApplicationController.getInstance().getApplicationContext());
            } else if (type.equalsIgnoreCase("REFRESH")) {
                LocationUpdaterHttpHelper locUpdater = new LocationUpdaterHttpHelper();
                Location loc = LocationController.getInstance().getLastKnownLocation();
                if (loc != null) {
                    String latitude = loc.getLatitude() + "";
                    String longitude = loc.getLongitude() + "";
                    if (authToken != null) {
                        locUpdater.execute(authToken, latitude, longitude);
                    }
                } else {
                    // TODO: Notify the user that the update location flow
                    // has not worked.
                }
            }
        }
    });
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

/**
 * Handles setting up the notification./* w w  w.j  a  v  a2  s. c o m*/
 * There are two situation in which we send a notification
 * First if there is more recent news than the last sync
 * Second if the news is concerned with the favorite character
 * @param context to use for getting preference information
 * @param newsItem  contains the newsItem information used to build the notification
 * @param notification_id identifier for the notification
 */
private void notifyNews(Context context, GuildViewerNewsItem newsItem, int notification_id) {

    // determine if we should send a notification
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean notificationsEnabled = prefs.getBoolean(context.getString(R.string.pref_enable_notifications_key),
            Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));
    long lastNotification = prefs.getLong(context.getString(R.string.pref_last_notification), 0L);
    boolean timeToNotify = newsItem.getTimestamp() > lastNotification;

    // we can notify for both new news and for favorite character news
    if (notificationsEnabled
            && (timeToNotify || notification_id == GUILD_VIEWER_FAVORITE_CHARACTER_NOTIFICATION)) {

        // build the information to put into the notification
        int iconId = R.drawable.ic_launcher;
        String title = context.getString(R.string.app_name);

        String news = String.format("%s %s %s", newsItem.getCharacter(),
                Utility.getNewsTypeVerb(context, newsItem.getType()),
                Utility.containsItem(newsItem.getType())
                        ? ((newsItem.getItem() != null) ? newsItem.getItem().getName() : "")
                        : ((newsItem.getAchievement() != null) ? newsItem.getAchievement().getTitle() : ""));
        String contentText = String.format(context.getString(R.string.format_notification), news);

        // set the notification to clear after a click
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(iconId)
                .setContentTitle(title).setContentText(contentText).setOnlyAlertOnce(true).setAutoCancel(true);

        // Open the app when the user clicks on the notification.
        Intent resultIntent = new Intent(context, NewsListActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context).addParentStack(NewsListActivity.class)
                .addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(resultPendingIntent);

        // we can notify for two reasons but lets just always have one notification at a time
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(GUILD_VIEWER_NOTIFICATION_ID, mBuilder.build());
    }
}

From source file:com.aware.Aware.java

/**
 * Starts a plugin. Expects the package name of the plugin.<br/>
 * It checks if the plugin does exist on the phone. If it doesn't, it will request the user to install it automatically.
 * @param context//from  w  w w. j  a  v a2s . c  o  m
 * @param package_name
 */
public static void startPlugin(Context context, String package_name) {
    //Check if plugin is installed. If not, ask user to download it.
    Cursor is_installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null,
            Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null, null);
    if (is_installed != null && is_installed.moveToFirst()) {
        //We might just have it cached, but not installed
        if (isClassAvailable(context, package_name, "Plugin")) {
            //it's installed, start it!
            Intent plugin = new Intent();
            plugin.setClassName(package_name, package_name + ".Plugin");
            context.startService(plugin);
            if (Aware.DEBUG)
                Log.d(TAG, package_name + " started...");

            ContentValues rowData = new ContentValues();
            rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON);
            context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData,
                    Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null);
            is_installed.close();
            return;
        }
        is_installed.close();
    }

    HttpResponse response = new Https(awareContext)
            .dataGET("https://api.awareframework.com/index.php/plugins/get_plugin/" + package_name);
    if (response != null && response.getStatusLine().getStatusCode() == 200) {
        try {
            String data = EntityUtils.toString(response.getEntity());
            if (data.equals("[]"))
                return;

            JSONObject json_package = new JSONObject(data);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setSmallIcon(R.drawable.ic_stat_aware_plugin_dependency);
            mBuilder.setContentTitle("AWARE");
            mBuilder.setContentText("Plugin missing: " + json_package.getString("title") + ". Tap to install.");
            mBuilder.setDefaults(Notification.DEFAULT_ALL);
            mBuilder.setAutoCancel(true);

            Intent pluginIntent = new Intent(context, DownloadPluginService.class);
            pluginIntent.putExtra("package_name", package_name);
            pluginIntent.putExtra("is_update", false);

            PendingIntent clickIntent = PendingIntent.getService(context, 0, pluginIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(clickIntent);
            NotificationManager notManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notManager.notify(json_package.getInt("id"), mBuilder.build());

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

From source file:com.apotheosis.acceleration.monitor.MainMenuActivity.java

private void startCollection(String name) {
    collector.setFileName(name);/*from   w ww .  j  ava2s  .  co m*/
    collector.start();
    pauseAccel.setText("Finish");

    if (getSupportActionBar() != null)
        getSupportActionBar().setTitle("Data Collection In Progress");

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder notification = new NotificationCompat.Builder(MainMenuActivity.this);
    notification.setSmallIcon(R.drawable.ic_launcher);
    notification.setContentTitle("Acceleration Monitor");
    notification.setContentText("Data Collection in Progress");

    Intent pendingIntent = new Intent(MainMenuActivity.this, MainMenuActivity.class);
    pendingIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    PendingIntent contentIntent = PendingIntent.getActivity(MainMenuActivity.this, 0, pendingIntent, 0);

    notification.setContentIntent(contentIntent);
    notification.setOngoing(true);

    nm.notify(R.string.app_name, notification.build());
}

From source file:net.helff.wificonnector.WifiConnectivityService.java

protected void sendNotification(String msg) {
    Log.i(TAG, "send notification: " + msg);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.launchericon, msg, System.currentTimeMillis());

    Intent intent = new Intent(this, WifiConnectorActivity.class);
    intent.setAction("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.LAUNCHER");
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    notification.setLatestEventInfo(this.getApplicationContext(), "WifiConnector", msg, pendingIntent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(1, notification);

}

From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java

@Override
protected void onHandleIntent(Intent intent) {
    // initialize

    // extract details
    Server server = intent.getParcelableExtra("server");
    String directory = intent.getStringExtra("directory");
    String filename = intent.getStringExtra("filename");

    // get the json parser from the application
    JsonParser jsonParser = new JsonParser();

    // start the ball rolling...
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker(String.format(getString(R.string.notif_ticker), filename))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large))
            .setSmallIcon(R.drawable.ic_stat_notif_small)
            .setContentTitle(String.format(getString(R.string.notif_title), filename))
            .setContentText(getString(R.string.notif_content_init))
            // to avoid NPE on android 2.x where content intent is required
            // set an empty content intent
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true);

    // notify user that upload is starting
    mgr.notify(NOTIFICATION_ID, builder.build());

    // reset ticker for any subsequent notifications
    builder.setTicker(null);/*from w ww  . j  ava 2s.c  o  m*/

    AbstractHttpClient client = CustomHTTPClient.getHttpClient();

    // enable digest authentication
    if (server.getUsername() != null && !server.getUsername().equals("")) {
        Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());

        client.getCredentialsProvider().setCredentials(
                new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials);
    }

    final File file = new File(directory, filename);
    final long length = file.length();

    try {
        CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new CustomMultiPartEntity.ProgressListener() {
                    @Override
                    public void transferred(long num) {
                        // calculate percentage

                        //System.out.println("transferred: " + num);

                        int progress = (int) ((num * 100) / length);

                        builder.setContentText(String.format(getString(R.string.notif_content), progress));

                        mgr.notify(NOTIFICATION_ID, builder.build());
                    }
                });

        multipart.addPart(file.getName(), new FileBody(file));

        HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content");
        httpRequest.setEntity(multipart);

        HttpResponse serverResponse = client.execute(httpRequest);

        BasicResponseHandler handler = new BasicResponseHandler();
        JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject();

        if (!reply.has("outcome")) {
            throw new RuntimeException(getString(R.string.invalid_response));
        } else {
            // remove the 'upload in-progress' notification
            mgr.cancel(NOTIFICATION_ID);

            String outcome = reply.get("outcome").getAsString();

            if (outcome.equals("success")) {

                String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString();

                Intent resultIntent = new Intent(this, UploadCompletedActivity.class);
                // populate it
                resultIntent.putExtra("server", server);
                resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE);
                resultIntent.putExtra("filename", filename);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // the notification id for the 'completed upload' notification
                // each completed upload will have a different id
                int notifCompletedID = (int) System.currentTimeMillis();

                builder.setContentTitle(getString(R.string.notif_title_uploaded))
                        .setContentText(String.format(getString(R.string.notif_content_uploaded), filename))
                        .setContentIntent(
                                // we set the (2nd param request code to completedID)
                                // see http://tinyurl.com/kkcedju
                                PendingIntent.getActivity(this, notifCompletedID, resultIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT))
                        .setAutoCancel(true).setOngoing(false);

                mgr.notify(notifCompletedID, builder.build());

            } else {
                JsonElement elem = reply.get("failure-description");

                if (elem.isJsonPrimitive()) {
                    throw new RuntimeException(elem.getAsString());
                } else if (elem.isJsonObject())
                    throw new RuntimeException(
                            elem.getAsJsonObject().get("domain-failure-description").getAsString());
            }
        }

    } catch (Exception e) {
        builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false);

        mgr.notify(NOTIFICATION_ID, builder.build());
    }
}