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.haha01haha01.harail.DatabaseDownloader.java

private boolean extractDb(File zip_path, NotificationManager notifyManager, Notification.Builder builder) {
    builder.setContentText("Unzipping...");
    notifyManager.notify(1, builder.build());
    File irw_folder = new File(Environment.getExternalStorageDirectory(), "irw_gtfs");
    if (irw_folder.exists()) {
        if (irw_folder.isDirectory()) {
            for (String file : irw_folder.list()) {
                new File(irw_folder, file).delete();
            }/*from   w  ww .j  a v a  2 s.  c om*/
        } else {
            irw_folder.delete();
        }
    }
    if (!irw_folder.exists()) {
        if (!irw_folder.mkdir()) {
            builder.setContentText("Makedir failed").setSmallIcon(android.R.drawable.ic_dialog_alert)
                    .setProgress(0, 0, false);
            notifyManager.notify(1, builder.build());
            return false;
        }
    }
    unpackZip(irw_folder, zip_path);
    builder.setContentText("Finished").setProgress(0, 0, false).setSmallIcon(android.R.drawable.ic_dialog_info);
    notifyManager.notify(1, builder.build());
    return true;
}

From source file:com.fastbootmobile.rssdemo.PushReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "ACTION : " + intent.getAction()); // Debug log the intent "action"

    // Get the shared preferences for OwnPush keys
    SharedPreferences pref = context.getApplicationContext().getSharedPreferences(OwnPushClient.PREF_PUSH,
            Context.MODE_PRIVATE);

    if (intent.getAction().equals(OwnPushClient.INTENT_RECEIVE)) {

        // This is a push message

        Log.d(TAG, "Decrypt : " + intent.getExtras().getString(OwnPushClient.EXTRA_DATA));

        OwnPushCrypto fp = new OwnPushCrypto(); // Create a crypto object for decrypt

        // Get the app key pair from shared preferences (these have been confirmed by the register intent)
        OwnPushCrypto.AppKeyPair keys = fp.getKey(pref.getString(OwnPushClient.PREF_PUBLIC_KEY, ""),
                pref.getString(OwnPushClient.PREF_PRIVATE_KEY, ""));

        // Decrypt the message from the intent extra data
        String msg = fp.decryptFromIntent(intent.getExtras(), BuildConfig.APP_PUBLIC_KEY, keys);

        JSONObject jObj;//from w  w  w  . j  av  a  2  s.c  o m
        if (msg != null) {
            Log.e(TAG, "RSS : " + msg);

            try {
                // Decode the JOSN data in the message
                jObj = new JSONObject(msg);

                Intent i = new Intent(Intent.ACTION_VIEW); // Create the intent
                i.setData(Uri.parse(jObj.getString("link"))); // Set the data using URI (these are web links)

                // Convert to pending intent
                PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), i,
                        0);

                // Create the notification
                Notification n = new Notification.Builder(context.getApplicationContext())
                        .setContentTitle("OwnPush RSS") // Main Title
                        .setContentText(jObj.getString("title")) // Set content
                        .setContentIntent(pIntent) // Add the pending intent
                        .setSmallIcon(R.drawable.ic_done).setAutoCancel(true) // Remove notification if opened
                        .build();

                n.defaults |= Notification.DEFAULT_SOUND; // Make some noise on push

                // Get the notification manager and display notification
                NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(notification_num, n);

                // Increase the notification counter by 1
                notification_num++;

            } catch (Exception e) {
                return;
            }

        }
    }
}

From source file:com.getmarco.weatherstationviewer.gcm.StationGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received./*w  ww. ja v  a  2  s . co m*/
 */
private void sendNotification(String message) {
    Intent intent = new Intent(this, StationListActivity.class);
    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("Station update").setContentText(message)
            .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);

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

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

From source file:com.android.marrowbone.anysoftboard.ChewbaccaUncaughtExceptionHandler.java

public void uncaughtException(Thread thread, Throwable ex) {
    Log.e(TAG, "Caught an unhandled exception!!! ", ex);
    boolean ignore = false;

    // https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
    String stackTrace = Log.getStackTrace(ex);
    if (ex instanceof NullPointerException && stackTrace != null && stackTrace.contains(
            "android.inputmethodservice.IInputMethodSessionWrapper.executeMessage(IInputMethodSessionWrapper.java")) {
        // https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
        Log.w(TAG, "An OS bug has been adverted. Move along, there is nothing to see here.");
        ignore = true;//from  w  w  w  .j a va  2s  .c o m
    }

    if (!ignore && AnyApplication.getConfig().useChewbaccaNotifications()) {
        String appName = DeveloperUtils.getAppDetails(mApp);

        final CharSequence utcTimeDate = DateFormat.format("kk:mm:ss dd.MM.yyyy", new Date());
        final String newline = DeveloperUtils.NEW_LINE;
        String logText = "Hi. It seems that we have crashed.... Here are some details:" + newline
                + "****** UTC Time: " + utcTimeDate + newline + "****** Application name: " + appName + newline
                + "******************************" + newline + "****** Exception type: "
                + ex.getClass().getName() + newline + "****** Exception message: " + ex.getMessage() + newline
                + "****** Trace trace:" + newline + stackTrace + newline;
        logText += "******************************" + newline + "****** Device information:" + newline
                + DeveloperUtils.getSysInfo();
        if (ex instanceof OutOfMemoryError
                || (ex.getCause() != null && ex.getCause() instanceof OutOfMemoryError)) {
            logText += "******************************\n" + "****** Memory:" + newline + getMemory();
        }
        logText += "******************************" + newline + "****** Log-Cat:" + newline
                + Log.getAllLogLines();

        String crashType = ex.getClass().getSimpleName() + ": " + ex.getMessage();
        Intent notificationIntent = new Intent(mApp, SendBugReportUiActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationIntent.putExtra(SendBugReportUiActivity.EXTRA_KEY_BugReportDetails,
                (Parcelable) new SendBugReportUiActivity.BugReportDetails(ex, logText));

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

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mApp);
        builder.setSmallIcon(R.drawable.notification_error_icon)
                .setTicker(mApp.getText(R.string.ime_crashed_ticker))
                .setContentTitle(mApp.getText(R.string.ime_name))
                .setContentText(mApp.getText(R.string.ime_crashed_sub_text))
                .setSubText(
                        BuildConfig.DEBUG ? crashType : null/*not showing the type of crash in RELEASE mode*/)
                .setWhen(System.currentTimeMillis()).setContentIntent(contentIntent).setAutoCancel(true)
                .setOnlyAlertOnce(true).setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

        // notifying
        NotificationManager notificationManager = (NotificationManager) mApp
                .getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1, builder.build());
    }
    // and sending to the OS
    if (!ignore && mOsDefaultHandler != null) {
        Log.i(TAG, "Sending the exception to OS exception handler...");
        mOsDefaultHandler.uncaughtException(thread, ex);
    }

    Thread.yield();
    //halting the process. No need to continue now. I'm a dead duck.
    System.exit(0);
}

From source file:at.ac.uniklu.mobile.sportal.notification.GCMIntentService.java

@Override
protected void onMessage(Context context, Intent intent) {
    /* Default case. The notification tickle tells the app to fetch new notifications
     * from the campus server. */
    if (intent.hasExtra("collapse_key")
            && intent.getStringExtra("collapse_key").equals("notification-tickle")) {
        Analytics.onEvent(Analytics.EVENT_GCM_MSG_NOTIFICATIONTICKLE);
        GCMUtils.notifyUser(context);/*from  w  w  w.ja v a2  s . c o m*/
    }
    /* A message text with an optional URL */
    else if (intent.hasExtra("type") && intent.getStringExtra("type").equals("broadcastmessage")) {
        Analytics.onEvent(Analytics.EVENT_GCM_MSG_BROADCAST);

        String message = intent.getStringExtra("message");
        String url = null;

        if (intent.hasExtra("url")) {
            url = intent.getStringExtra("url");
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder nb = GCMUtils.getBroadcastMessageNotification(this, message, url);
        notificationManager.notify(Studentportal.NOTIFICATION_GCM_BROADCASTMESSAGE, nb.build());
    }
    /* Service message. Tells the client to invalidate it's ID and re-register. Might
     * be useful some day if the database on the campus server needs to be cleaned/rebuilt/invalidated. */
    else if (intent.hasExtra("type") && intent.getStringExtra("type").equals("refresh-registration")) {
        GCMUtils.clearRegistrationId(context);
        GCMUtils.register(context);
    } else {
        Analytics.onEvent(Analytics.EVENT_GCM_MSG_UNKNOWN);
    }
}

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

/**
 * To generate a notification to inform the user that server has sent a message.
 * //ww  w .j  a  v  a2  s .  co m
 * @param count
 * @param count 
 */
private static void generateNotification(Context context, String message, String count) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MainActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(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;
    try {
        int countValue = Integer.parseInt(count);
        notification.number = countValue;
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    // // Play default notification sound
    notification.defaults = Notification.DEFAULT_SOUND;
    notificationManager.notify(0, notification);
}

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

public void displayNotification(RemoteMessage.Notification remoteNotification, Map<String, String> messageMap) {

    String username = messageMap.get("username");
    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(remoteNotification.getTitle())
            .setContentText(username + " : " + remoteNotification.getBody()).setSmallIcon(R.mipmap.ic_launcher)
            .build();//from   www  . j a v  a  2s.co  m

    //Sets an ID for the notification
    int notificationID = 001;

    int numMessages = 0;

    //Gets an instance of the NotificationManager service
    NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    //Builds the notification and issues it
    notifyManager.notify(notificationID, notification);
}

From source file:be.ehb.fallwear.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.//ww  w . j  a  va 2 s  .  c  o  m
 */
private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    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.drawable.ic_stat_ic_notification).setContentTitle("GCM Message")
            .setContentText(message).setAutoCancel(true).setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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

From source file:com.iniciacomunicacion.devicenotification.DeviceNotification.java

/**
 * Adds notification// w ww  .  j a  v a  2s . c o m
 * 
 * @param callbackContext, Callback context of the request from Cordova
 * @param title, The title of notification
 * @param message, The content text of the notification
 * @param Id, The unique ID of the notification
 * @param seconds
 */
public void add(CallbackContext callbackContext, String ticker, String title, String message, int id) {

    Resources res = DeviceNotification.context.getResources();
    int ic_launcher = res.getIdentifier("icon", "drawable", cordova.getActivity().getPackageName());

    /* Version 4.x
    NotificationManager notificationManager = (NotificationManager)DeviceNotification.activity.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification.Builder(DeviceNotification.Context)
    .setTicker(ticker)
    .setContentTitle(title)
    .setContentText(message)
    .setSmallIcon(ic_launcher)
    .setWhen(System.currentTimeMillis())
    .setAutoCancel(true)
    .build();
    notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
    notificationManager.notify(id, notification);*/

    //Version 2.x
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(DeviceNotification.activity)
            .setSmallIcon(ic_launcher).setWhen(System.currentTimeMillis()).setContentTitle(title)
            .setContentText(message).setTicker(ticker);
    Intent resultIntent = new Intent(DeviceNotification.activity, DeviceNotification.activity.getClass());
    PendingIntent resultPendingIntent = PendingIntent.getActivity(DeviceNotification.activity, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotifyMgr = (NotificationManager) DeviceNotification.activity
            .getSystemService(android.content.Context.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(id, mBuilder.build());
}

From source file:ca.rmen.android.poetassistant.PoemAudioExport.java

private void notifyPoemAudioFailed() {
    Log.v(TAG, "notifyPoemAudioFailed");
    cancelNotifications();//w  ww  .j  a v a2s. c o m
    Notification notification = new NotificationCompat.Builder(mContext).setAutoCancel(true)
            .setContentTitle(mContext.getString(R.string.share_poem_audio_error_notification_title))
            .setContentText(mContext.getString(R.string.share_poem_audio_error_notification_message))
            .setContentIntent(getMainActivityIntent()).setSmallIcon(Share.getNotificationIcon()).build();
    NotificationManager notificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(EXPORT_FINISH_NOTIFICATION_ID, notification);
}