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:com.ferdi2005.secondgram.voip.VoIPService.java

private void startRinging() {
    FileLog.d("starting ringing for call " + call.id);
    dispatchStateChanged(STATE_WAITING_INCOMING);
    //ringtone=RingtoneManager.getRingtone(this, Settings.System.DEFAULT_RINGTONE_URI);
    //ringtone.play();
    SharedPreferences prefs = getSharedPreferences("Notifications", MODE_PRIVATE);
    ringtonePlayer = new MediaPlayer();
    ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override/*from  w  w w  . j av a2  s .c om*/
        public void onPrepared(MediaPlayer mediaPlayer) {
            ringtonePlayer.start();
        }
    });
    ringtonePlayer.setLooping(true);
    ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
    try {
        String notificationUri;
        if (prefs.getBoolean("custom_" + user.id, false))
            notificationUri = prefs.getString("ringtone_path_" + user.id,
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
        else
            notificationUri = prefs.getString("CallsRingtonePath",
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
        ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
        ringtonePlayer.prepareAsync();
    } catch (Exception e) {
        FileLog.e(e);
        if (ringtonePlayer != null) {
            ringtonePlayer.release();
            ringtonePlayer = null;
        }
    }
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    int vibrate;
    if (prefs.getBoolean("custom_" + user.id, false))
        vibrate = prefs.getInt("calls_vibrate_" + user.id, 0);
    else
        vibrate = prefs.getInt("vibrate_calls", 0);
    if ((vibrate != 2 && vibrate != 4
            && (am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE
                    || am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL))
            || (vibrate == 4 && am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)) {
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        long duration = 700;
        if (vibrate == 1)
            duration /= 2;
        else if (vibrate == 3)
            duration *= 2;
        vibrator.vibrate(new long[] { 0, duration, 500 }, 0);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
            && !((KeyguardManager) getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode()
            && NotificationManagerCompat.from(this).areNotificationsEnabled()) {
        showIncomingNotification();
        FileLog.d("Showing incoming call notification");
    } else {
        FileLog.d("Starting incall activity for incoming call");
        try {
            PendingIntent.getActivity(VoIPService.this, 12345,
                    new Intent(VoIPService.this, VoIPActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0)
                    .send();
        } catch (Exception x) {
            FileLog.e("Error starting incall activity", x);
        }
    }

}

From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java

synchronized void setPlayerState(PlayerState playerState) {
    Log.i(TAG, String.format("%s -> %s (%s)", this.playerState.name(), playerState.name(), currentPlaying));

    this.playerState = playerState;

    if (this.playerState == PAUSED) {
        lifecycleSupport.serializeDownloadQueue();
    }/*  ww  w  .j  a v a2s  . c  o m*/

    if (this.playerState == PlayerState.STARTED) {
        Util.requestAudioFocus(this);
    }

    boolean showWhenPaused = (this.playerState != PlayerState.STOPPED
            && Util.isNotificationAlwaysEnabled(this));
    boolean show = this.playerState == PlayerState.STARTED || showWhenPaused;

    Util.broadcastPlaybackStatusChange(this, this.playerState);
    Util.broadcastA2dpPlayStatusChange(this, this.playerState, instance);

    if (this.playerState == PlayerState.STARTED || this.playerState == PlayerState.PAUSED) {
        // Set remote control
        updateRemoteControl();
    }

    // Update widget
    UltraSonicAppWidgetProvider4x1.getInstance().notifyChange(this, this,
            this.playerState == PlayerState.STARTED, false);
    UltraSonicAppWidgetProvider4x2.getInstance().notifyChange(this, this,
            this.playerState == PlayerState.STARTED, true);
    UltraSonicAppWidgetProvider4x3.getInstance().notifyChange(this, this,
            this.playerState == PlayerState.STARTED, false);
    UltraSonicAppWidgetProvider4x4.getInstance().notifyChange(this, this,
            this.playerState == PlayerState.STARTED, false);
    SubsonicTabActivity tabInstance = SubsonicTabActivity.getInstance();

    if (show) {
        if (tabInstance != null) {
            // Only update notification is player state is one that will change the icon
            if (this.playerState == PlayerState.STARTED || this.playerState == PlayerState.PAUSED) {
                if (Util.isNotificationEnabled(this)) {
                    final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                    notificationManager.notify(NOTIFICATION_ID, buildForegroundNotification());
                }
                tabInstance.showNowPlaying();
            }
        }
    } else {
        if (tabInstance != null) {
            stopForeground(true);
            tabInstance.hideNowPlaying();
        }
    }

    if (this.playerState == STARTED) {
        scrobbler.scrobble(this, currentPlaying, false);
    } else if (this.playerState == COMPLETED) {
        scrobbler.scrobble(this, currentPlaying, true);
    }

    if (playerState == STARTED && positionCache == null) {
        positionCache = new PositionCache();
        Thread thread = new Thread(positionCache);
        thread.start();
    } else if (playerState != STARTED && positionCache != null) {
        positionCache.stop();
        positionCache = null;
    }
}

From source file:android_network.hetnet.vpn_service.AdapterRule.java

private void updateRule(Rule rule, boolean root, List<Rule> listAll) {
    SharedPreferences wifi = context.getSharedPreferences("wifi", Context.MODE_PRIVATE);
    SharedPreferences other = context.getSharedPreferences("other", Context.MODE_PRIVATE);
    SharedPreferences apply = context.getSharedPreferences("apply", Context.MODE_PRIVATE);
    SharedPreferences screen_wifi = context.getSharedPreferences("screen_wifi", Context.MODE_PRIVATE);
    SharedPreferences screen_other = context.getSharedPreferences("screen_other", Context.MODE_PRIVATE);
    SharedPreferences roaming = context.getSharedPreferences("roaming", Context.MODE_PRIVATE);
    SharedPreferences notify = context.getSharedPreferences("notify", Context.MODE_PRIVATE);

    if (rule.wifi_blocked == rule.wifi_default)
        wifi.edit().remove(rule.info.packageName).apply();
    else//from  w  w w .  j  a  v a  2  s.co m
        wifi.edit().putBoolean(rule.info.packageName, rule.wifi_blocked).apply();

    if (rule.other_blocked == rule.other_default)
        other.edit().remove(rule.info.packageName).apply();
    else
        other.edit().putBoolean(rule.info.packageName, rule.other_blocked).apply();

    if (rule.apply)
        apply.edit().remove(rule.info.packageName).apply();
    else
        apply.edit().putBoolean(rule.info.packageName, rule.apply).apply();

    if (rule.screen_wifi == rule.screen_wifi_default)
        screen_wifi.edit().remove(rule.info.packageName).apply();
    else
        screen_wifi.edit().putBoolean(rule.info.packageName, rule.screen_wifi).apply();

    if (rule.screen_other == rule.screen_other_default)
        screen_other.edit().remove(rule.info.packageName).apply();
    else
        screen_other.edit().putBoolean(rule.info.packageName, rule.screen_other).apply();

    if (rule.roaming == rule.roaming_default)
        roaming.edit().remove(rule.info.packageName).apply();
    else
        roaming.edit().putBoolean(rule.info.packageName, rule.roaming).apply();

    if (rule.notify)
        notify.edit().remove(rule.info.packageName).apply();
    else
        notify.edit().putBoolean(rule.info.packageName, rule.notify).apply();

    rule.updateChanged(context);
    Log.i(TAG, "Updated " + rule);

    List<Rule> listModified = new ArrayList<>();
    for (String pkg : rule.related) {
        for (Rule related : listAll)
            if (related.info.packageName.equals(pkg)) {
                related.wifi_blocked = rule.wifi_blocked;
                related.other_blocked = rule.other_blocked;
                related.apply = rule.apply;
                related.screen_wifi = rule.screen_wifi;
                related.screen_other = rule.screen_other;
                related.roaming = rule.roaming;
                related.notify = rule.notify;
                listModified.add(related);
            }
    }

    List<Rule> listSearch = (root ? new ArrayList<>(listAll) : listAll);
    listSearch.remove(rule);
    for (Rule modified : listModified)
        listSearch.remove(modified);
    for (Rule modified : listModified)
        updateRule(modified, false, listSearch);

    if (root) {
        notifyDataSetChanged();
        NotificationManagerCompat.from(context).cancel(rule.info.applicationInfo.uid);
        ServiceSinkhole.reload("rule changed", context);
    }
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//from  ww  w  .j av a  2 s.  com

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

    Intent markRead = new Intent(context, MarkReadSecondAccService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    AppSettings settings = AppSettings.getInstance(context);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverTwo.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setAutoCancel(true).setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(9, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, messageLong);
        }

        // Light Flow notification
        sendToLightFlow(context, title, messageLong);
    }
}

From source file:com.irccloud.android.Notifications.java

private void showMessageNotifications(String ticker) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    String text = "";
    String weartext = "";
    ArrayList<Notification> notifications = getMessageNotifications();

    int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
    boolean notify = false;
    if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
        notify = true;// w  w w.j a va 2 s . c  o m

    if (notifications.size() > 0 && notify) {
        int lastbid = notifications.get(0).bid;
        int count = 0;
        long[] eids = new long[notifications.size()];
        String[] auto_messages = new String[notifications.size()];
        Notification last = null;
        count = 0;
        boolean show = false;
        for (Notification n : notifications) {
            if (n.bid != lastbid) {
                if (show) {
                    String title = last.chan;
                    if (title == null || title.length() == 0)
                        title = last.nick;
                    if (title == null || title.length() == 0)
                        title = last.network;

                    Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
                    replyIntent.putExtra("bid", last.bid);
                    replyIntent.putExtra("cid", last.cid);
                    replyIntent.putExtra("eids", eids);
                    replyIntent.putExtra("network", last.network);
                    if (last.buffer_type.equals("channel"))
                        replyIntent.putExtra("to", last.chan);
                    else
                        replyIntent.putExtra("to", last.nick);

                    String body = "";
                    if (last.buffer_type.equals("channel")) {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = "<b> " + last.nick + "</b> " + last.message;
                        else
                            body = "<b>&lt;" + last.nick + "&gt;</b> " + last.message;
                    } else {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = " " + last.nick + " " + last.message;
                        else
                            body = last.message;
                    }

                    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                            .notify(lastbid,
                                    buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text),
                                            count, replyIntent, Html.fromHtml(weartext), last.network,
                                            auto_messages));
                }
                lastbid = n.bid;
                text = "";
                weartext = "";
                count = 0;
                eids = new long[notifications.size()];
                show = false;
                auto_messages = new String[notifications.size()];
            }
            if (count < 3) {
                if (text.length() > 0)
                    text += "<br/>";
                if (n.buffer_type.equals("conversation") && n.message_type.equals("buffer_me_msg"))
                    text += " " + n.message;
                else if (n.buffer_type.equals("conversation"))
                    text += n.message;
                else if (n.message_type.equals("buffer_me_msg"))
                    text += "<b> " + n.nick + "</b> " + n.message;
                else
                    text += "<b>" + n.nick + "</b> " + n.message;
            }
            if (weartext.length() > 0)
                weartext += "<br/><br/>";
            if (n.message_type.equals("buffer_me_msg"))
                weartext += "<b> " + n.nick + "</b> " + n.message;
            else
                weartext += "<b>&lt;" + n.nick + "&gt;</b> " + n.message;

            if (n.buffer_type.equals("conversation")) {
                if (n.message_type.equals("buffer_me_msg"))
                    auto_messages[count] = " " + n.nick + " " + Html.fromHtml(n.message).toString();
                else
                    auto_messages[count] = Html.fromHtml(n.message).toString();
            } else {
                if (n.message_type.equals("buffer_me_msg"))
                    auto_messages[count] = " " + n.nick + " " + Html.fromHtml(n.message).toString();
                else
                    auto_messages[count] = n.nick + " said: " + Html.fromHtml(n.message).toString();
            }

            if (!n.shown) {
                n.shown = true;
                show = true;

                if (prefs.getBoolean("notify_sony", false)) {
                    long time = System.currentTimeMillis();
                    long sourceId = NotificationUtil.getSourceId(
                            IRCCloudApplication.getInstance().getApplicationContext(),
                            SonyExtensionService.EXTENSION_SPECIFIC_ID);
                    if (sourceId == NotificationUtil.INVALID_ID) {
                        Crashlytics.log(Log.ERROR, "IRCCloud",
                                "Sony LiveWare Manager not configured, disabling Sony notifications");
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean("notify_sony", false);
                        editor.commit();
                    } else {
                        ContentValues eventValues = new ContentValues();
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.EVENT_READ_STATUS,
                                false);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.DISPLAY_NAME,
                                n.nick);

                        if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.chan);
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.network);

                        if (n.message_type.equals("buffer_me_msg"))
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    " " + Html.fromHtml(n.message).toString());
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    Html.fromHtml(n.message).toString());

                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PERSONAL,
                                1);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PUBLISHED_TIME,
                                time);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.SOURCE_ID,
                                sourceId);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY,
                                String.valueOf(n.bid));

                        try {
                            IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                                    .insert(com.sonyericsson.extras.liveware.aef.notification.Notification.Event.URI,
                                            eventValues);
                        } catch (IllegalArgumentException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        } catch (SecurityException e) {
                            Log.e("IRCCloud", "Failed to insert event, is Live Ware Manager installed?", e);
                        } catch (SQLException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        }
                    }
                }

                if (prefs.getBoolean("notify_pebble", false)) {
                    String pebbleTitle = n.network + ":\n";
                    String pebbleBody = "";
                    if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                        pebbleTitle = n.chan + ":\n";

                    if (n.message_type.equals("buffer_me_msg"))
                        pebbleBody = " " + n.message;
                    else
                        pebbleBody = n.message;

                    if (n.nick != null && n.nick.length() > 0)
                        notifyPebble(n.nick, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                    else
                        notifyPebble(n.network, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                }
            }
            eids[count++] = n.eid;
            last = n;
        }

        if (show) {
            String title = last.chan;
            if (title == null || title.length() == 0)
                title = last.nick;
            if (title == null || title.length() == 0)
                title = last.network;

            Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
            replyIntent.putExtra("bid", last.bid);
            replyIntent.putExtra("cid", last.cid);
            replyIntent.putExtra("network", last.network);
            replyIntent.putExtra("eids", eids);
            if (last.buffer_type.equals("channel"))
                replyIntent.putExtra("to", last.chan);
            else
                replyIntent.putExtra("to", last.nick);

            String body = "";
            if (last.buffer_type.equals("channel")) {
                if (last.message_type.equals("buffer_me_msg"))
                    body = "<b> " + last.nick + "</b> " + last.message;
                else
                    body = "<b>&lt;" + last.nick + "&gt;</b> " + last.message;
            } else {
                if (last.message_type.equals("buffer_me_msg"))
                    body = " " + last.nick + " " + last.message;
                else
                    body = last.message;
            }
            NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                    .notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text),
                            count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
        }
    }
}

From source file:org.videolan.vlc.PlaybackService.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void showNotification() {
    try {//from w w  w .  j  a  v a  2s.  com
        MediaWrapper media = getCurrentMedia();
        if (media == null)
            return;
        Bitmap cover = AudioUtil.getCover(this, media, 64);
        String title = media.getTitle();
        String artist = Util.getMediaArtist(this, media);
        String album = Util.getMediaAlbum(this, media);
        Notification notification;

        if (media.isArtistUnknown() && media.isAlbumUnknown() && media.getNowPlaying() != null) {
            artist = media.getNowPlaying();
            album = "";
        }

        //Watch notification dismissed
        PendingIntent piStop = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_REMOTE_STOP),
                PendingIntent.FLAG_UPDATE_CURRENT);

        // add notification to status bar
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_vlc).setTicker(title + " - " + artist)
                .setAutoCancel(!MediaPlayer().isPlaying()).setOngoing(MediaPlayer().isPlaying())
                .setDeleteIntent(piStop);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(AudioPlayerContainerActivity.ACTION_SHOW_PLAYER);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        notificationIntent.putExtra(START_FROM_NOTIFICATION, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        if (AndroidUtil.isJellyBeanOrLater()) {
            Intent iBackward = new Intent(ACTION_REMOTE_BACKWARD);
            Intent iPlay = new Intent(ACTION_REMOTE_PLAYPAUSE);
            Intent iForward = new Intent(ACTION_REMOTE_FORWARD);
            PendingIntent piBackward = PendingIntent.getBroadcast(this, 0, iBackward,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent piPlay = PendingIntent.getBroadcast(this, 0, iPlay,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent piForward = PendingIntent.getBroadcast(this, 0, iForward,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            RemoteViews view = new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.notification);
            view.setImageViewBitmap(R.id.cover,
                    cover == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon) : cover);
            view.setTextViewText(R.id.songName, title);
            view.setTextViewText(R.id.artist, artist);
            view.setImageViewResource(R.id.play_pause,
                    MediaPlayer().isPlaying() ? R.drawable.ic_pause_w : R.drawable.ic_play_w);
            view.setOnClickPendingIntent(R.id.play_pause, piPlay);
            view.setOnClickPendingIntent(R.id.forward, piForward);
            view.setOnClickPendingIntent(R.id.stop, piStop);
            view.setOnClickPendingIntent(R.id.content, pendingIntent);

            RemoteViews view_expanded = new RemoteViews(BuildConfig.APPLICATION_ID,
                    R.layout.notification_expanded);
            view_expanded.setImageViewBitmap(R.id.cover,
                    cover == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon) : cover);
            view_expanded.setTextViewText(R.id.songName, title);
            view_expanded.setTextViewText(R.id.artist, artist);
            view_expanded.setTextViewText(R.id.album, album);
            view_expanded.setImageViewResource(R.id.play_pause,
                    MediaPlayer().isPlaying() ? R.drawable.ic_pause_w : R.drawable.ic_play_w);
            view_expanded.setOnClickPendingIntent(R.id.backward, piBackward);
            view_expanded.setOnClickPendingIntent(R.id.play_pause, piPlay);
            view_expanded.setOnClickPendingIntent(R.id.forward, piForward);
            view_expanded.setOnClickPendingIntent(R.id.stop, piStop);
            view_expanded.setOnClickPendingIntent(R.id.content, pendingIntent);

            if (AndroidUtil.isLolliPopOrLater()) {
                //Hide stop button on pause, we swipe notification to stop
                view.setViewVisibility(R.id.stop, MediaPlayer().isPlaying() ? View.VISIBLE : View.INVISIBLE);
                view_expanded.setViewVisibility(R.id.stop,
                        MediaPlayer().isPlaying() ? View.VISIBLE : View.INVISIBLE);
                //Make notification appear on lockscreen
                builder.setVisibility(Notification.VISIBILITY_PUBLIC);
            }

            notification = builder.build();
            notification.contentView = view;
            notification.bigContentView = view_expanded;
        } else {
            builder.setLargeIcon(
                    cover == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon) : cover)
                    .setContentTitle(title)
                    .setContentText(
                            AndroidUtil.isJellyBeanOrLater() ? artist : Util.getMediaSubtitle(this, media))
                    .setContentInfo(album).setContentIntent(pendingIntent);
            notification = builder.build();
        }

        startService(new Intent(this, PlaybackService.class));
        if (!AndroidUtil.isLolliPopOrLater() || MediaPlayer().isPlaying())
            startForeground(3, notification);
        else {
            stopForeground(false);
            NotificationManagerCompat.from(this).notify(3, notification);
        }
    } catch (NoSuchMethodError e) {
        // Compat library is wrong on 3.2
        // http://code.google.com/p/android/issues/detail?id=36359
        // http://code.google.com/p/android/issues/detail?id=36502
    }
}

From source file:com.cw.litenote.main.MainAct.java

@Override
protected void onDestroy() {
    System.out.println("MainAct / onDestroy");

    if (bluetooth_device_receiver != null) {
        try {//from   w  w  w  .  j a v a  2 s .com
            unregisterReceiver(bluetooth_device_receiver);
        } catch (Exception e) {
        }
        bluetooth_device_receiver = null;
    }

    // stop audio player
    if (BackgroundAudioService.mMediaPlayer != null)
        Audio_manager.stopAudioPlayer();

    // disconnect MediaBrowserCompat
    if ((mMediaBrowserCompat != null) && mMediaBrowserCompat.isConnected())
        mMediaBrowserCompat.disconnect();

    //hide notification
    NotificationManagerCompat.from(MainAct.mAct).cancel(BackgroundAudioService.id);

    mMediaBrowserCompat = null;

    super.onDestroy();
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences(
            "com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//ww w . ja va 2s.c o m

    Intent resultIntent = new Intent(context, SwitchAccountsRedirect.class);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

    Intent markRead = new Intent(context, MarkReadSecondAccService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    AppSettings settings = AppSettings.getInstance(context);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverTwo.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)).setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(9, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, messageLong);
        }

        // Light Flow notification
        sendToLightFlow(context, title, messageLong);
    }
}

From source file:com.secupwn.aimsicd.service.CellTracker.java

/**
 * Cancel and remove the persistent notification
 */
public void cancelNotification() {
    NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID);
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void notifySecondMentions(Context context, int secondAccount) {
    MentionsDataSource data = MentionsDataSource.getInstance(context);
    int numberNew = data.getUnreadCount(secondAccount);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//w  ww.j av  a 2s  . com

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name = null;
    String message;
    String messageLong;

    String tweetText = null;
    NotificationCompat.Action replyAction = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        SharedPreferences sharedPrefs = context.getSharedPreferences(
                "com.daiv.android.twitter_world_preferences",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        tweetText = data.getNewestMessage(secondAccount);
        messageLong = "<b>@" + name + "</b>: " + tweetText;
        largeIcon = getImage(context, name);

        Intent reply = null;

        sharedPrefs.edit().putString("from_notification_second", "@" + name).commit();
        long id = data.getLastIds(secondAccount)[0];
        PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0);
        sharedPrefs.edit().putLong("from_notification_long_second", id).commit();
        sharedPrefs.edit()
                .putString("from_notification_text_second",
                        "@" + name + ": "
                                + TweetLinkUtils.removeColorHtml(tweetText, AppSettings.getInstance(context)))
                .commit();

        // Create the remote input
        RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel("@" + name + " ").build();

        // Create the notification action
        replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_action_reply_dark,
                context.getResources().getString(R.string.noti_reply), replyPending).addRemoteInput(remoteInput)
                        .build();

    } else { // more than one mention
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
    }

    Intent markRead = new Intent(context, MarkReadSecondAccService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    AppSettings settings = AppSettings.getInstance(context);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverTwo.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setAutoCancel(true)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (numberNew == 1) {
        mBuilder.addAction(replyAction);
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        NotificationCompat.InboxStyle inbox = getMentionsInboxStyle(numberNew, secondAccount, context,
                TweetLinkUtils.removeColorHtml(message, settings));

        mBuilder.setStyle(inbox);
    }
    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(9, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (context
                .getSharedPreferences("com.daiv.android.twitter_world_preferences",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)
                .getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, messageLong);
        }

        // Light Flow notification
        sendToLightFlow(context, title, messageLong);
    }
}