Example usage for android.support.v4.app NotificationManagerCompat from

List of usage examples for android.support.v4.app NotificationManagerCompat from

Introduction

In this page you can find the example usage for android.support.v4.app NotificationManagerCompat from.

Prototype

public static NotificationManagerCompat from(Context context) 

Source Link

Usage

From source file:org.c99.wear_imessage.RemoteInputService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_REPLY.equals(action)) {
            JSONObject conversations = null, conversation = null;
            try {
                conversations = new JSONObject(
                        getSharedPreferences("data", 0).getString("conversations", "{}"));
            } catch (JSONException e) {
                conversations = new JSONObject();
            }/*from w  w w.ja v  a2 s .c o  m*/

            try {
                String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle");
                if (conversations.has(key)) {
                    conversation = conversations.getJSONObject(key);
                } else {
                    conversation = new JSONObject();
                    conversations.put(key, conversation);

                    long time = new Date().getTime();
                    String tmpStr = String.valueOf(time);
                    String last4Str = tmpStr.substring(tmpStr.length() - 5);
                    conversation.put("notification_id", Integer.valueOf(last4Str));
                    conversation.put("msgs", new JSONArray());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null || intent.hasExtra("reply")) {
                String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString()
                        : intent.getStringExtra("reply");

                if (intent.hasExtra(Intent.EXTRA_STREAM)) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                            .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true)
                            .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload);
                    NotificationManagerCompat.from(this).notify(1337, notification.build());

                    InputStream fileIn = null;
                    InputStream responseIn = null;
                    HttpURLConnection http = null;
                    try {
                        String filename = "";
                        int total = 0;
                        String type = getContentResolver()
                                .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
                        if (type == null || type.length() == 0)
                            type = "application/octet-stream";
                        fileIn = getContentResolver()
                                .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));

                        Cursor c = getContentResolver().query(
                                (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM),
                                new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null,
                                null);
                        if (c != null && c.moveToFirst()) {
                            total = c.getInt(0);
                            filename = c.getString(1);
                            c.close();
                        } else {
                            total = fileIn.available();
                        }

                        String boundary = UUID.randomUUID().toString();
                        http = (HttpURLConnection) new URL(
                                "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload")
                                        .openConnection();
                        http.setReadTimeout(60000);
                        http.setConnectTimeout(60000);
                        http.setDoOutput(true);
                        http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length()
                                + type.length() + intent.getStringExtra("handle").length()
                                + intent.getStringExtra("service").length() + reply.length() + 251);
                        http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                        OutputStream out = http.getOutputStream();
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("handle") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("service") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes());
                        out.write((reply + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename
                                + "\"\r\n").getBytes());
                        out.write(("Content-Type: " + type + "\r\n\r\n").getBytes());

                        byte[] buffer = new byte[8192];
                        int count = 0;
                        int n = 0;
                        while (-1 != (n = fileIn.read(buffer))) {
                            out.write(buffer, 0, n);
                            count += n;

                            float progress = (float) count / (float) total;
                            if (progress < 1.0f)
                                notification.setProgress(1000, (int) (progress * 1000), false);
                            else
                                notification.setProgress(0, 0, true);
                            NotificationManagerCompat.from(this).notify(1337, notification.build());
                        }

                        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
                        out.flush();
                        out.close();
                        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            responseIn = http.getInputStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.i("iMessage", "Upload result: " + sb.toString());
                            try {
                                if (conversation != null) {
                                    JSONArray msgs = conversation.getJSONArray("msgs");
                                    JSONObject m = new JSONObject();
                                    m.put("msg", filename);
                                    m.put("service", intent.getStringExtra("service"));
                                    m.put("handle", intent.getStringExtra("handle"));
                                    m.put("type", "sent_file");
                                    msgs.put(m);

                                    while (msgs.length() > 10) {
                                        msgs.remove(0);
                                    }

                                    GCMIntentService.notify(getApplicationContext(),
                                            intent.getIntExtra("notification_id", 0), msgs, intent, true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            responseIn = http.getErrorStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.e("iMessage", "Upload failed: " + sb.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (responseIn != null)
                                responseIn.close();
                        } catch (Exception ignore) {
                        }
                        try {
                            if (http != null)
                                http.disconnect();
                        } catch (Exception ignore) {
                        }
                        try {
                            fileIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    NotificationManagerCompat.from(this).cancel(1337);
                } else if (reply.length() > 0) {
                    URL url = null;
                    try {
                        url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "")
                                + "/send?service=" + intent.getStringExtra("service") + "&handle="
                                + intent.getStringExtra("handle") + "&msg="
                                + URLEncoder.encode(reply, "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    HttpURLConnection conn;

                    try {
                        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setUseCaches(false);

                    BufferedReader reader = null;

                    try {
                        if (conn.getInputStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
                        }
                    } catch (IOException e) {
                        if (conn.getErrorStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
                        }
                    }

                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.disconnect();
                    try {
                        if (conversation != null) {
                            JSONArray msgs = conversation.getJSONArray("msgs");
                            JSONObject m = new JSONObject();
                            m.put("msg", reply);
                            m.put("service", intent.getStringExtra("service"));
                            m.put("handle", intent.getStringExtra("handle"));
                            m.put("type", "sent");
                            msgs.put(m);

                            while (msgs.length() > 10) {
                                msgs.remove(0);
                            }

                            GCMIntentService.notify(getApplicationContext(),
                                    intent.getIntExtra("notification_id", 0), msgs, intent, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                SharedPreferences.Editor e = getSharedPreferences("data", 0).edit();
                e.putString("conversations", conversations.toString());
                e.apply();
            }
        }
    }
}

From source file:com.irateam.vkplayer.notifications.DownloadNotification.java

public static void successfulDownload(Context context, int audioCount) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_ab_done)
            .setContentTitle(context.getString(R.string.notification_successful_download))
            .setContentText(context.getString(R.string.notification_successful_download_count) + audioCount);
    NotificationManagerCompat.from(context).notify(FINAL_DOWNLOAD_NOTIFICATION_ID, builder.build());
}

From source file:com.reallynourl.nourl.fmpfoldermusicplayer.ui.notifications.MediaNotification.java

public static void remove(Service service) {
    service.stopForeground(true);
    NotificationManagerCompat.from(service).cancel(NOTIFICATION_ID);
}

From source file:nl.hnogames.domoticz.Utils.NotificationUtil.java

public static void sendSimpleNotification(String title, String text, final Context context) {
    if (UsefulBits.isEmpty(title) || UsefulBits.isEmpty(text) || context == null)
        return;/*from ww  w .j  a v  a  2  s  . c o  m*/
    if (prefUtil == null)
        prefUtil = new SharedPrefUtil(context);
    prefUtil.addUniqueReceivedNotification(text);
    prefUtil.addLoggedNotification(new SimpleDateFormat("yyyy-MM-dd hh:mm ").format(new Date()) + text);

    List<String> suppressedNot = prefUtil.getSuppressedNotifications();
    List<String> alarmNot = prefUtil.getAlarmNotifications();
    try {
        if (prefUtil.isNotificationsEnabled() && suppressedNot != null && !suppressedNot.contains(text)) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.domoticz_white)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
                    .setContentTitle(alarmNot != null && alarmNot.contains(text)
                            ? context.getString(R.string.alarm) + ": " + title
                            : title)
                    .setContentText(alarmNot != null && alarmNot.contains(text)
                            ? context.getString(R.string.alarm) + ": " + text
                            : text)
                    .setGroupSummary(true).setGroup(GROUP_KEY_NOTIFICATIONS).setAutoCancel(true);

            if (!prefUtil.OverWriteNotifications())
                NOTIFICATION_ID = text.hashCode();
            if (prefUtil.getNotificationVibrate())
                builder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
            if (!UsefulBits.isEmpty(prefUtil.getNotificationSound()))
                builder.setSound(Uri.parse(prefUtil.getNotificationSound()));

            Intent targetIntent = new Intent(context, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, targetIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(contentIntent);

            if (prefUtil.isNotificationsEnabled() && alarmNot != null && alarmNot.contains(text)) {
                Intent stopAlarmIntent = new Intent(context, StopAlarmButtonListener.class);
                PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(context, 78578, stopAlarmIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                builder.addAction(android.R.drawable.ic_delete, "Stop", pendingAlarmIntent);
            }

            if (prefUtil.showAutoNotifications()) {
                builder.extend(new NotificationCompat.CarExtender()
                        .setUnreadConversation(getUnreadConversation(context, text)));
            }

            NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build());
            if (prefUtil.isNotificationsEnabled() && alarmNot != null && alarmNot.contains(text)) {
                Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                if (alert == null) {
                    alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    if (alert == null)
                        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                }
                if (alert != null) {
                    Intent ringtoneServiceStartIntent = new Intent(context, RingtonePlayingService.class);
                    ringtoneServiceStartIntent.putExtra("ringtone-uri", alert.toString());
                    context.startService(ringtoneServiceStartIntent);

                    if (prefUtil.getAlarmTimer() > 0) {
                        Thread.sleep(prefUtil.getAlarmTimer() * 1000);
                        Intent stopIntent = new Intent(context, RingtonePlayingService.class);
                        context.stopService(stopIntent);
                    }
                }
            }
        }
    } catch (Exception ex) {
        Log.i("NOTIFY", ex.getMessage());
    }
}

From source file:com.example.android.elizachat.ResponderService.java

private void showNotification() {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Sent: " + mLastResponse);
    }/*ww  w . java2  s . c  om*/
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.eliza)).setContentText(mLastResponse)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bg_eliza))
            .setSmallIcon(R.drawable.bg_eliza).setPriority(NotificationCompat.PRIORITY_MIN);

    Intent intent = new Intent(ACTION_RESPONSE);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
    Notification notification = builder.extend(new NotificationCompat.WearableExtender()
            .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_full_reply,
                    getString(R.string.reply), pendingIntent).addRemoteInput(
                            new RemoteInput.Builder(EXTRA_REPLY).setLabel(getString(R.string.reply)).build())
                            .build()))
            .build();
    NotificationManagerCompat.from(this).notify(0, notification);
}

From source file:com.example.android.wearable.elizachat.ResponderService.java

private void showNotification() {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Sent: " + mLastResponse);
    }/*from  w  w w  .j a  v  a 2  s .c  o  m*/
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.eliza)).setContentText(mLastResponse)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bg_eliza))
            .setSmallIcon(R.drawable.bg_eliza).setPriority(NotificationCompat.PRIORITY_DEFAULT);

    Intent intent = new Intent(ACTION_RESPONSE);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
    Notification notification = builder.extend(new NotificationCompat.WearableExtender()
            .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_full_reply,
                    getString(R.string.reply), pendingIntent).addRemoteInput(
                            new RemoteInput.Builder(EXTRA_REPLY).setLabel(getString(R.string.reply)).build())
                            .build()))
            .build();
    NotificationManagerCompat.from(this).notify(0, notification);
}

From source file:com.binil.pushnotification.GcmIntentService.java

private void displayNotification(PendingIntent pi, String title, String msg) {

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(((BitmapDrawable) ContextCompat.getDrawable(getApplication(), R.drawable.ic_launcher))
                    .getBitmap())//  www . j  a  v a  2 s  .  c om
            .setContentTitle(title).setContentText(msg).setContentIntent(pi).setTicker(msg)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL);

    NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
    manager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:com.wizardsofm.deskclock.alarms.AlarmNotifications.java

public static void showLowPriorityNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying low priority notification for alarm instance: " + instance.mId);

    mcontext = context;/*from  w  ww  .  ja va  2  s  .c  om*/

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context).setShowWhen(false)
            .setContentTitle(context.getString(com.wizardsofm.deskclock.R.string.alarm_alert_predismiss_title))
            .setContentText(AlarmUtils.getAlarmText(context, instance, true /* includeLabel */))
            .setColor(ContextCompat.getColor(context, com.wizardsofm.deskclock.R.color.default_background))
            .setSmallIcon(com.wizardsofm.deskclock.R.drawable.stat_notify_alarm).setAutoCancel(false)
            .setSortKey(createSortKey(instance)).setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);

    if (Utils.isNOrLater()) {
        notification.setGroup(UPCOMING_GROUP_KEY);
    }

    // Setup up hide notification
    Intent hideIntent = AlarmStateManager.createStateChangeIntent(context, AlarmStateManager.ALARM_DELETE_TAG,
            instance, AlarmInstance.HIDE_NOTIFICATION_STATE);
    notification.setDeleteIntent(PendingIntent.getService(context, instance.hashCode(), hideIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.PREDISMISSED_STATE);
    notification.addAction(com.wizardsofm.deskclock.R.drawable.ic_alarm_off_24dp,
            context.getString(com.wizardsofm.deskclock.R.string.alarm_alert_dismiss_now_text),
            PendingIntent.getService(context, instance.hashCode(), dismissIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content action if instance is owned by alarm
    Intent viewAlarmIntent = createViewAlarmIntent(context, instance);
    notification.setContentIntent(PendingIntent.getActivity(context, instance.hashCode(), viewAlarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(instance.hashCode(), notification.build());
    updateAlarmGroupNotification(context);
}

From source file:com.example.android.wearable.wear.wearnotifications.StandaloneMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate()");

    setContentView(R.layout.activity_main);
    setAmbientEnabled();/*  w  w w.  j a  v  a  2s.  c om*/

    mMainRelativeLayout = (RelativeLayout) findViewById(R.id.mainRelativeLayout);
    mSpinner = (Spinner) findViewById(R.id.spinner);

    mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,
            NOTIFICATION_STYLES);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    mSpinner.setAdapter(adapter);
    mSpinner.setOnItemSelectedListener(this);

}

From source file:com.sumang.chatdemo.MyFirebaseMessagingService.java

/**
 * Handle time allotted to BroadcastReceivers.
 *//*from w w  w.jav  a 2  s .  com*/
private void handleNow(String title, String messageBody) {
    Log.d(TAG, "Short lived task is done.");
    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).setGroup("ABC")
            .setGroupSummary(true).setSmallIcon(R.drawable.messenger_bubble_small_white)
            .setColor(getResources().getColor(R.color.colorAccent)).setContentTitle(title)
            .setContentText(messageBody).setAutoCancel(true).setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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