Example usage for android.graphics BitmapFactory decodeResource

List of usage examples for android.graphics BitmapFactory decodeResource

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeResource.

Prototype

public static Bitmap decodeResource(Resources res, int id) 

Source Link

Document

Synonym for #decodeResource(Resources,int,android.graphics.BitmapFactory.Options) with null Options.

Usage

From source file:at.fhooe.mcm.saap.facebook.HelloFacebookSampleActivity.java

private void postPhoto() {
    Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);
    if (canPresentShareDialogWithPhotos) {
        FacebookDialog shareDialog = createShareDialogBuilderForPhoto(image).build();
        uiHelper.trackPendingDialogCall(shareDialog.present());
    } else if (hasPublishPermission()) {
        Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image,
                new Request.Callback() {
                    @Override/*from   w  w w .  jav  a 2s.  c om*/
                    public void onCompleted(Response response) {
                        showPublishResult(getString(R.string.photo_post), response.getGraphObject(),
                                response.getError());
                    }
                });
        request.executeAsync();
    } else {
        pendingAction = PendingAction.POST_PHOTO;
    }
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

private void incomingImage() {
    Log.setLogLevel(6);//from w w  w . j  a v  a 2  s.c om
    Log.d("incomingImage", "call");
    iv_recievedfile = (ImageView) v.findViewById(R.id.iv_recievedfile);
    pb_uploading.setVisibility(ProgressBar.GONE);

    if (isvideoMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        downloadFile(subject, RECIEVED_VIDEO);
    } else if (isaudioMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        downloadFile(subject, RECIEVED_AUDIO);
    } else if (islocationMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_map_icon);
        iv_recievedfile.setImageBitmap(b);
    } else if (iscontactMsg(subject)) {
        tv_msg_info.setText("0");
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_contact_icon);
        iv_recievedfile.setImageBitmap(b);
    } else if (isimageMsg(subject)) {
        downloadFile(subject, RECIEVED_IMAGE);
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);

    } else {
        text_view.setVisibility(TextView.VISIBLE);
        iv_recievedfile.setVisibility(ImageView.GONE);

    }
}

From source file:com.tingbacke.wearmaps.MobileActivity.java

private Notification getBasicNotification(String stack) {
    String title = "Vstra Hamnen";
    TextView tv = (TextView) findViewById(R.id.textView3);
    String text = tv.getText().toString();

    // Here I determine the vibration pattern for the notification
    long[] pattern = { 0, 200, 0 };

    /*//  ww  w  .  j a va 2 s  .  c  o  m
            // This seems only to be for adding longer texts to a notification...
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.setBigContentTitle(title);
    */
    /*
    Spannable sb = new SpannableString("Bold this and italic that.");
    sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 14, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    */

    NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender()
            .setBackground(BitmapFactory.decodeResource(getResources(), R.mipmap.turn));

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.addLine(Html.fromHtml("<b>Turning Torso</b>"));
    inboxStyle.addLine(Html.fromHtml("<b>453m away</b>"));

    return new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.icon_mdpi).setContentTitle(title)
            .setContentText(text)
            //.setStyle(bigPic)
            //.setStyle(inboxStyle)
            .extend(extender)
            //.setStyle(bigTextStyle)
            .setVibrate(pattern).setGroup(stack).build();
}

From source file:com.daskiworks.ghwatch.backend.UnreadNotificationsService.java

protected void fireAndroidNotification(NotificationStream newStream, NotificationStream oldStream) {
    if (newStream == null || !PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY, true))
        return;//from   ww w  .  j  a  va2  s .  c o m

    Log.d(TAG, "fireAndroidNotification count before filter " + newStream.size());
    newStream = filterForAndroidNotification(newStream);
    Log.d(TAG, "fireAndroidNotification count after filter " + newStream.size());
    if (newStream.isNewNotification(oldStream)) {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.github_notification)
                .setContentTitle(context.getString(R.string.an_title_more))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        mBuilder.setAutoCancel(true);

        if (newStream.size() > 1)
            mBuilder.setNumber(newStream.size());

        boolean allFromOne = newStream.allNotificationsFromSameRepository();

        if (newStream.size() == 1 || allFromOne) {
            // only one repository
            Notification n = newStream.get(0);
            Bitmap b = ImageLoader.getInstance(context).loadImageWithFileLevelCache(n.getRepositoryAvatarUrl());
            if (b != null) {
                mBuilder.setLargeIcon(b);
            } else {
                mBuilder.setLargeIcon(
                        BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification));
            }
            mBuilder.setContentText(n.getRepositoryFullName());
        } else {
            mBuilder.setLargeIcon(
                    BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification));
        }

        Intent resultIntent = null;
        if (newStream.size() == 1) {
            mBuilder.setContentTitle(context.getString(R.string.an_title_one));
            Notification n = newStream.get(0);
            mBuilder.setContentText(n.getRepositoryFullName() + ": " + n.getSubjectTitle());
            NotificationCompat.BigTextStyle btStyle = new NotificationCompat.BigTextStyle();
            btStyle.bigText(n.getSubjectTitle());
            btStyle.setSummaryText(n.getRepositoryFullName());
            mBuilder.setStyle(btStyle);
            Intent actionIntent = new Intent(context, MarkNotifiationAsReadReceiver.class);
            actionIntent.putExtra(MarkNotifiationAsReadReceiver.INTENT_EXTRA_KEY_ID, n.getId());
            mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_mark_read),
                    PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT));

            resultIntent = new Intent(context, MainActivity.class);
        } else {
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            for (Notification n : newStream) {
                if (allFromOne) {
                    inboxStyle.addLine(n.getSubjectTitle());
                } else {
                    inboxStyle.addLine(n.getRepositoryFullName() + ": " + n.getSubjectTitle());
                }
            }
            if (allFromOne)
                inboxStyle.setSummaryText(newStream.get(0).getRepositoryFullName());
            else
                inboxStyle.setSummaryText(" ");
            mBuilder.setStyle(inboxStyle);

            Intent actionIntent = new Intent(context, MainActivity.class);
            actionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            actionIntent.setAction(MainActivity.INTENT_ACTION_DISMISS_ALL);
            mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_all_read),
                    PendingIntent.getActivity(context, 0, actionIntent, 0));

            resultIntent = new Intent(context, MainActivity.class);
        }

        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        resultIntent.setAction(MainActivity.INTENT_ACTION_SHOW);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);
        mBuilder.setContentIntent(resultPendingIntent);

        String nsound = PreferencesUtils.getString(context, PreferencesUtils.PREF_NOTIFY_SOUND, null);
        Log.d(TAG, "Notification sound from preference: " + nsound);
        if (nsound != null) {
            mBuilder.setSound(Uri.parse(nsound));
        }
        if (PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY_VIBRATE, true)) {
            mBuilder.setVibrate(new long[] { 0, 300, 100, 150, 100, 150 });
        }

        mBuilder.setLights(0xffffffff, 100, 4000);

        // mId allows you to update the notification later on.
        Utils.getNotificationManager(context).notify(ANDROID_NOTIFICATION_ID, mBuilder.build());
        ActivityTracker.sendEvent(context, ActivityTracker.CAT_NOTIF, "new_notif",
                "notif count: " + newStream.size(), Long.valueOf(newStream.size()));
    } else if (newStream.isEmpty()) {
        // #54 dismiss previous android notification if no any Github notification is available (as it was read on another device)
        Utils.getNotificationManager(context).cancel(ANDROID_NOTIFICATION_ID);
    }
}

From source file:com.google.sample.castcompanionlibrary.cast.player.VideoCastControllerFragment.java

private void showImage(final Uri url) {
    if (mImageAsyncTask != null) {
        mImageAsyncTask.cancel(true);//  w w w  .j  av a 2s  .  c o  m
    }
    if (null == url) {
        mCastController.setImage(
                BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.dummy_album_art_large));
        return;
    }
    if (null != mUrlAndBitmap && mUrlAndBitmap.isMatch(url)) {
        // we can reuse mBitmap
        mCastController.setImage(mUrlAndBitmap.mBitmap);
        return;
    }
    mUrlAndBitmap = null;
    mImageAsyncTask = new FetchBitmapTask() {
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (null != bitmap) {
                mUrlAndBitmap = new UrlAndBitmap();
                mUrlAndBitmap.mBitmap = bitmap;
                mUrlAndBitmap.mUrl = url;
                mCastController.setImage(bitmap);
            }
            if (this == mImageAsyncTask) {
                mImageAsyncTask = null;
            }
        }
    };
    mImageAsyncTask.start(url);
}

From source file:com.blueshit.activity.ChatActivity.java

/**
 * onActivityResult// w  w  w . ja v  a  2s .  co m
 */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CODE_EXIT_GROUP) {
        setResult(RESULT_OK);
        finish();
        return;
    }
    if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
        switch (resultCode) {
        case RESULT_CODE_COPY: // ??
            EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1)));
            // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
            // ((TextMessageBody) copyMsg.getBody()).getMessage()));
            clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
            break;
        case RESULT_CODE_DELETE: // ?
            EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
            conversation.removeMessage(deleteMsg.getMsgId());
            adapter.refresh();
            listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1);
            break;

        case RESULT_CODE_FORWARD: // ??
            //            EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0));
            //            Intent intent = new Intent(this, ForwardMessageActivity.class);
            //            intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
            //            startActivity(intent);

            break;

        default:
            break;
        }
    }
    if (resultCode == RESULT_OK) { // ?
        if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
            // ?
            EMChatManager.getInstance().clearConversation(toChatUsername);
            adapter.refresh();
        } else if (requestCode == REQUEST_CODE_CAMERA) { // ??
            if (cameraFile != null && cameraFile.exists())
                sendPicture(cameraFile.getAbsolutePath());
        } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ??

            int duration = data.getIntExtra("dur", 0);
            String videoPath = data.getStringExtra("path");
            File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
            Bitmap bitmap = null;
            FileOutputStream fos = null;
            try {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                if (bitmap == null) {
                    EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon);
                }
                fos = new FileOutputStream(file);

                bitmap.compress(CompressFormat.JPEG, 100, fos);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fos = null;
                }
                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }

            }
            sendVideo(videoPath, file.getAbsolutePath(), duration / 1000);

        } else if (requestCode == REQUEST_CODE_LOCAL) { // ??
            if (data != null) {
                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                    sendPicByUri(selectedImage);
                }
            }
        } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ??
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    sendFile(uri);
                }
            }

        } else if (requestCode == REQUEST_CODE_MAP) { // 
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            if (locationAddress != null && !locationAddress.equals("")) {
                more(more);
                sendLocationMsg(latitude, longitude, "", locationAddress);
            } else {
                String st = getResources().getString(R.string.unable_to_get_loaction);
                Toast.makeText(this, st, Toast.LENGTH_SHORT).show();
            }
            // ???
        } else if (requestCode == REQUEST_CODE_TEXT || requestCode == REQUEST_CODE_VOICE
                || requestCode == REQUEST_CODE_PICTURE || requestCode == REQUEST_CODE_LOCATION
                || requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
            // 
            if (!TextUtils.isEmpty(clipboard.getText())) {
                String pasteText = clipboard.getText().toString();
                if (pasteText.startsWith(COPY_IMAGE)) {
                    // ??path
                    sendPicture(pasteText.replace(COPY_IMAGE, ""));
                }

            }
        } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ???
            EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
            addUserToBlacklist(deleteMsg.getFrom());
        } else if (conversation.getMsgCount() > 0) {
            adapter.refresh();
            setResult(RESULT_OK);
        } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
            adapter.refresh();
        }
    }
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

/**
 * Raises a notification with a biggest earthquake with each sync
 *
 * @param notifyValues data with the biggest recent earthquake
 *//* ww w.j  av a  2  s. co m*/
private void sendNotification(ContentValues notifyValues) {

    Context context = getContext();

    if (Utilities.getNotificationsPrefs(context) && !Utilities.checkForeground(context)) {

        //checking the last update and notify if it' the first of the day
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String lastNotificationKey = context.getString(R.string.sharedprefs_key_lastnotification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= DateUtils.DAY_IN_MILLIS) {
            Intent intent = new Intent(context, DetailActivity.class);

            double latitude = notifyValues.getAsDouble(EarthquakeColumns.LATITUDE);
            double longitude = notifyValues.getAsDouble(EarthquakeColumns.LONGITUDE);
            LatLng latLng = new LatLng(latitude, longitude);

            String distance = context.getString(R.string.earthquake_distance,
                    LocationUtils.getDistance(latLng, LocationUtils.getLocation(context)));

            String magnitude = context.getString(R.string.earthquake_magnitude,
                    notifyValues.getAsDouble(EarthquakeColumns.MAG));
            String date = Utilities.getRelativeDate(notifyValues.getAsLong(EarthquakeColumns.TIME));

            double depth = notifyValues.getAsDouble(EarthquakeColumns.DEPTH);

            intent.putExtra(Feature.MAGNITUDE, notifyValues.getAsDouble(EarthquakeColumns.MAG));
            intent.putExtra(Feature.PLACE, notifyValues.getAsString(EarthquakeColumns.PLACE));
            intent.putExtra(Feature.DATE, date);
            intent.putExtra(Feature.LINK, notifyValues.getAsString(EarthquakeColumns.URL));
            intent.putExtra(Feature.LATLNG, latLng);
            intent.putExtra(Feature.DISTANCE, distance);
            intent.putExtra(Feature.DEPTH, depth);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, EarthquakeObject.NOTIFICATION_ID_1,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

            builder.setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true)
                    .setContentTitle(context.getString(R.string.earthquake_statistics_largest))
                    .setContentText(context.getString(R.string.earthquake_magnitude,
                            notifyValues.get(EarthquakeColumns.MAG)))
                    .setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_info_black_24dp)
                    .setLargeIcon(largeIcon).setTicker(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(notifyValues.get(EarthquakeColumns.PLACE).toString() + "\n" + magnitude
                                    + "\n" + context.getString(R.string.earthquake_depth, depth) + "\n"
                                    + distance + "\n" + date))
                    .setGroup(EarthquakeObject.NOTIFICATION_GROUP).setGroupSummary(true);

            NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
            managerCompat.notify(EarthquakeObject.NOTIFICATION_ID_1, builder.build());

            //refreshing last sync
            boolean success = prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).commit();
        }
    }
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

public void notifyWeather() {
    Context context = getContext();
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
    boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
            Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));

    if (displayNotifications) {

        String lastNotificationKey = context.getString(R.string.pref_last_notification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= getNotificationTimeGap()) {
            // Last sync was more than 1 day ago, let's send a notification with the weather.
            String locationQuery = WeatherUtil.getPreferredLocation(context);

            Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery,
                    System.currentTimeMillis());

            // we'll query our contentProvider, as always
            Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null,
                    null, null);/*from ww w  .  ja v  a 2s  .  co  m*/

            if (cursor.moveToFirst()) {
                int weatherId = cursor.getInt(INDEX_WEATHER_ID);
                double high = cursor.getDouble(INDEX_MAX_TEMP);
                double low = cursor.getDouble(INDEX_MIN_TEMP);
                String desc = cursor.getString(INDEX_SHORT_DESC);

                int iconId = WeatherUtil.getIconResourceForWeatherCondition(weatherId);
                Resources resources = context.getResources();
                Bitmap largeIcon = BitmapFactory.decodeResource(resources,
                        WeatherUtil.getArtResourceForWeatherCondition(weatherId));
                String title = getTitle();

                // Define the text of the forecast.
                String contentText = String.format(context.getString(R.string.format_notification), desc,
                        WeatherUtil.formatTemperature(context, high),
                        WeatherUtil.formatTemperature(context, low));

                // NotificationCompatBuilder is a very convenient way to build backward-compatible
                // notifications.  Just throw in some data.
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext())
                        .setColor(resources.getColor(R.color.weather4u_light_blue)).setSmallIcon(iconId)
                        .setLargeIcon(largeIcon).setContentTitle(title).setContentText(contentText);
                mBuilder.setAutoCancel(true);

                // Make something interesting happen when the user clicks on the notification.
                // In this case, opening the app is sufficient.
                Intent resultIntent = new Intent(context, MainActivity.class);

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);

                NotificationManager mNotificationManager = (NotificationManager) getContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                // WEATHER_NOTIFICATION_ID allows you to update the notification later on.
                mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build());

                //refreshing last sync
                SharedPreferences.Editor editor = prefs.edit();
                editor.putLong(lastNotificationKey, System.currentTimeMillis());
                editor.commit();
            }
            cursor.close();
        }
    }
}

From source file:com.andreadec.musicplayer.MusicService.java

private void updateNotificationMessage() {
    /* Update remote control client */
    if (Build.VERSION.SDK_INT >= 14) {
        if (currentPlayingItem == null) {
            remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
        } else {//from   www.j  ava  2  s .  com
            if (isPlaying()) {
                remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
            } else {
                remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
            }
            RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, currentPlayingItem.getTitle());
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, currentPlayingItem.getArtist());
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST,
                    currentPlayingItem.getArtist());
            metadataEditor.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, getDuration());
            if (currentPlayingItem.hasImage()) {
                metadataEditor.putBitmap(METADATA_KEY_ARTWORK, currentPlayingItem.getImage());
            } else {
                metadataEditor.putBitmap(METADATA_KEY_ARTWORK, icon.copy(icon.getConfig(), false));
            }
            metadataEditor.apply();
        }
    }

    /* Update notification */
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.audio_white);
    //notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    notificationBuilder.setOngoing(true);

    int playPauseIcon = isPlaying() ? R.drawable.pause : R.drawable.play;
    //int playPauseString = isPlaying() ? R.string.pause : R.string.play;
    notificationBuilder.setContentIntent(pendingIntent);

    String notificationMessage = "";
    if (currentPlayingItem == null) {
        notificationMessage = getResources().getString(R.string.noSong);
    } else {
        if (currentPlayingItem.getArtist() != null && !currentPlayingItem.getArtist().equals(""))
            notificationMessage = currentPlayingItem.getArtist() + " - ";
        notificationMessage += currentPlayingItem.getTitle();
    }

    /*notificationBuilder.addAction(R.drawable.previous, getResources().getString(R.string.previous), previousPendingIntent);
    notificationBuilder.addAction(playPauseIcon, getResources().getString(playPauseString), playpausePendingIntent);
    notificationBuilder.addAction(R.drawable.next, getResources().getString(R.string.next), nextPendingIntent);*/
    notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
    notificationBuilder.setContentText(notificationMessage);

    notification = notificationBuilder.build();

    RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.layout_notification);

    if (currentPlayingItem == null) {
        notificationLayout.setTextViewText(R.id.textViewArtist, getString(R.string.app_name));
        notificationLayout.setTextViewText(R.id.textViewTitle, getString(R.string.noSong));
        notificationLayout.setImageViewBitmap(R.id.imageViewNotification,
                BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    } else {
        notificationLayout.setTextViewText(R.id.textViewArtist, currentPlayingItem.getArtist());
        notificationLayout.setTextViewText(R.id.textViewTitle, currentPlayingItem.getTitle());
        Bitmap image = currentPlayingItem.getImage();
        if (image != null) {
            notificationLayout.setImageViewBitmap(R.id.imageViewNotification, image);
        } else {
            notificationLayout.setImageViewBitmap(R.id.imageViewNotification,
                    BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
        }
    }
    notificationLayout.setOnClickPendingIntent(R.id.buttonNotificationQuit, quitPendingIntent);
    notificationLayout.setOnClickPendingIntent(R.id.buttonNotificationPrevious, previousPendingIntent);
    notificationLayout.setImageViewResource(R.id.buttonNotificationPlayPause, playPauseIcon);
    notificationLayout.setOnClickPendingIntent(R.id.buttonNotificationPlayPause, playpausePendingIntent);
    notificationLayout.setOnClickPendingIntent(R.id.buttonNotificationNext, nextPendingIntent);
    notification.bigContentView = notificationLayout;

    notificationManager.notify(Constants.NOTIFICATION_MAIN, notification);
}

From source file:app.view.chat.ChatActivity.java

/**
 * onActivityResult// www  .  ja  va  2  s .co m
 */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CODE_EXIT_GROUP) {
        setResult(RESULT_OK);
        finish();
        return;
    }
    if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
        switch (resultCode) {
        case RESULT_CODE_COPY: // ??
            EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1)));
            if (copyMsg.getType() == EMMessage.Type.IMAGE) {
                ImageMessageBody imageBody = (ImageMessageBody) copyMsg.getBody();
                // ???
                clipboard.setText(COPY_IMAGE + imageBody.getLocalUrl());
            } else {
                // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
                // ((TextMessageBody) copyMsg.getBody()).getMessage()));
                clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
            }
            break;
        case RESULT_CODE_DELETE: // ?
            EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
            conversation.removeMessage(deleteMsg.getMsgId());
            adapter.refresh();
            listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1);
            break;

        case RESULT_CODE_FORWARD: // ??
            EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0));
            Intent intent = new Intent(this, ForwardMessageActivity.class);
            intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
            startActivity(intent);

            break;

        default:
            break;
        }
    }
    if (resultCode == RESULT_OK) { // ?
        if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
            // ?
            EMChatManager.getInstance().clearConversation(toChatUsername);
            adapter.refresh();
        } else if (requestCode == REQUEST_CODE_CAMERA) { // ??
            if (cameraFile != null && cameraFile.exists())
                sendPicture(cameraFile.getAbsolutePath());
        } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ??

            int duration = data.getIntExtra("dur", 0);
            String videoPath = data.getStringExtra("path");
            File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
            Bitmap bitmap = null;
            FileOutputStream fos = null;
            try {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                if (bitmap == null) {
                    EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon);
                }
                fos = new FileOutputStream(file);

                bitmap.compress(CompressFormat.JPEG, 100, fos);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fos = null;
                }
                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }

            }
            sendVideo(videoPath, file.getAbsolutePath(), duration / 1000);

        } else if (requestCode == REQUEST_CODE_LOCAL) { // ??
            if (data != null) {
                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                    sendPicByUri(selectedImage);
                }
            }
        } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ??
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    sendFile(uri);
                }
            }

        } else if (requestCode == REQUEST_CODE_MAP) { // 
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            if (locationAddress != null && !locationAddress.equals("")) {
                more(more);
                sendLocationMsg(latitude, longitude, "", locationAddress);
            } else {
                Toast.makeText(this, "????", Toast.LENGTH_SHORT).show();
            }
            // ???
        } else if (requestCode == REQUEST_CODE_TEXT) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_VOICE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_PICTURE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_LOCATION) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
            // 
            if (!TextUtils.isEmpty(clipboard.getText())) {
                String pasteText = clipboard.getText().toString();
                if (pasteText.startsWith(COPY_IMAGE)) {
                    // ??path
                    sendPicture(pasteText.replace(COPY_IMAGE, ""));
                }

            }
        } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ???
            EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
            addUserToBlacklist(deleteMsg.getFrom());
        } else if (conversation.getMsgCount() > 0) {
            adapter.refresh();
            setResult(RESULT_OK);
        } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
            adapter.refresh();
        }
    }
}