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:com.footprint.cordova.plugin.localnotification.Options.java

/**
 * Converts an resource to Bitmap.//from   ww w . j  a  v  a  2s. c o  m
 *
 * @param icon
 *      The resource name
 * @return
 *      The corresponding bitmap
 */
private Bitmap getIconFromRes(String icon) {
    Resources res = LocalNotification.context.getResources();
    int iconId = 0;

    iconId = getIconValue(packageName, icon);

    if (iconId == 0) {
        iconId = getIconValue("android", icon);
    }

    if (iconId == 0) {
        iconId = android.R.drawable.ic_menu_info_details;
    }

    Bitmap bmp = BitmapFactory.decodeResource(res, iconId);

    return bmp;
}

From source file:com.chilliworks.chillisource.googleplay.core.GCMService.java

private void generateNotification(Context context, HashMap<String, String> inParams) {
    //if the application is active then pass this information on to the application.
    if (CSApplication.get() != null && CSApplication.get().isActive() == true) {
        //build the array of keys and values
        int dwNumEntries = inParams.size();
        String[] astrKeys = new String[dwNumEntries];
        String[] astrValues = new String[dwNumEntries];
        int dwCount = 0;
        for (String strKey : inParams.keySet()) {
            astrKeys[dwCount] = strKey;// www  .j a v  a 2  s  .  co m
            astrValues[dwCount] = inParams.get(strKey);
            dwCount++;
        }

        // Send this to the native side of the engine.
        mNativeInterface.OnRemoteNotificationReceived(astrKeys, astrValues);
    }
    // Otherwise display a notification.
    else {
        String strTitle = context.getString(ResourceHelper.GetDynamicResourceIDForField(context,
                ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_STRING, "app_name"));
        String strMessage = inParams.get("message");

        Intent notificationIntent = new Intent(context, CSActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        Bitmap largeIconBitmap = null;
        int largeIconID = ResourceHelper.GetDynamicResourceIDForField(context,
                ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify_large");

        //If no large icon then use the small icon
        if (largeIconID == 0) {
            largeIconID = ResourceHelper.GetDynamicResourceIDForField(context,
                    ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify");
        }

        if (largeIconID > 0) {
            largeIconBitmap = BitmapFactory.decodeResource(context.getResources(), largeIconID);
        }

        Notification notification = new NotificationCompat.Builder(context).setContentTitle(strTitle)
                .setContentText(strMessage)
                .setSmallIcon(ResourceHelper.GetDynamicResourceIDForField(context,
                        ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify"))
                .setLargeIcon(largeIconBitmap).setContentIntent(intent).build();

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }
}

From source file:br.com.GUI.aulas.Agenda.java

public void atualizarInterface(ArrayList<Aula> exibir) {

    for (Aula l : exibir) {
        String dataAula = l.getDiaAula() + "/" + l.getMesAula() + "/" + l.getAnoAula();
        String anoAula = l.getHoraAula() + ":" + l.getMinutoAula();

        String confirmacao;/*  ww w.ja v  a  2s  .  c  o m*/
        if (l.getConfirmacaoAulaAluno() == 1 && l.getConfirmacaoAulaPersonal() == 1) {
            confirmacao = "Confirmada!";
        } else if (l.getConfirmacaoAulaAluno() == 0 && l.getConfirmacaoAulaPersonal() == 0) {
            confirmacao = "Cancelada";
        } else {
            confirmacao = "Aguardando Confirmao...";
        }

        RowItemAgendamentos item = new RowItemAgendamentos(
                BitmapFactory.decodeResource(getResources(), R.drawable.horarios), l.getUsuarioAluno(),
                dataAula, anoAula, confirmacao);
        listaAulas.add(item);
    }

    CustomAdapterAgendamentos adapter = new CustomAdapterAgendamentos(getActivity(), listaAulas);
    lstAulas.setAdapter(adapter);
    registerForContextMenu(lstAulas);

    lstAulas.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            Intent intent = new Intent(getActivity(), ConfirmarAula.class);
            intent.putExtra("aula", al.get(arg2).getCodAula());
            startActivity(intent);

        }
    });
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

public long storeAppobjInDatabase(DbObj obj, Context context) {
    long localId = -1; // if replace entry, set ID
    Gson gs = new Gson();

    Postdata postdata = gs.fromJson(obj.getJson().toString(), Postdata.class);
    long hash = obj.getHash();
    byte[] raw = null;
    if (postdata.datatype.equals(Postdata.TYPE_STREAM)) {
        int iconid = DataManager.getIconid(postdata.localUri, postdata.mimetype);
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), iconid);
        raw = BitmapHelper.bitmapToBytes(icon);
    } else if (postdata.datatype.equals(Postdata.TYPE_TEXT_WITH_LINK)) {
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_html);
        raw = BitmapHelper.bitmapToBytes(icon);
    } else {/*from www  .  j  a v  a2 s  .  c om*/
        raw = obj.getRaw();
    }

    String feedname = obj.getFeedName();
    long parentid = 0;
    try {
        if (obj.getJson().has("target_relation") && obj.getJson().getString("target_relation").equals("parent")
                && obj.getJson().has("target_hash")) {
            parentid = objIdForHash(obj.getJson().getLong("target_hash"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    DbUser usr = obj.getSender();
    String sender = "";
    if (usr != null) {
        sender = usr.getName();
    }

    return addObjectByPostdata(localId, postdata, hash, raw, parentid, feedname, sender);
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private void warnOnError() {
    mBuilder.setStyle(new NotificationCompat.InboxStyle()
            .setBigContentTitle(getString(R.string.notifTitle) + " - No URLs")
            .addLine(getString(R.string.notifNoURLToCheck)).addLine(getString(R.string.notifAddURL))
            .setSummaryText(Integer.toString(checkedCount) + " " + getString(R.string.notifChecked) + " / "
                    + Integer.toString(censoredCount) + " " + getString(R.string.notifPossBlock)))
            .setSmallIcon(R.drawable.ic_stat_waiting)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_ooni_large))
            .setPriority(Notification.PRIORITY_MAX).setTicker(getString(R.string.notifTitle) + " - No URLs")
            .setAutoCancel(false);/*from   www. ja va  2s .  com*/
    mBuilder.setProgress(0, 0, false);

    mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());

    Intent newIntent = new Intent();
    newIntent.setAction(ProgressFragment.ORG_BROADCAST);
    newIntent.putExtra(ProgressFragment.ORG_BROADCAST, ProgressFragment.NO_URLS);
    sendBroadcast(newIntent);
}

From source file:com.appdevper.mediaplayer.ui.PlaybackControlsFragment.java

private Bitmap downloadBitmap(String mediaId) {
    String url = MusicProvider.getInstance().getMusic(mediaId)
            .getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);
    final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
    metaRetriever.setDataSource(url, new HashMap<String, String>());
    try {/*from  ww w .j a v  a  2  s .  com*/
        final byte[] art = metaRetriever.getEmbeddedPicture();
        return BitmapFactory.decodeByteArray(art, 0, art.length);
    } catch (Exception e) {
        Log.d(TAG, "Couldn't create album art: " + e.getMessage());
        return BitmapFactory.decodeResource(getResources(), R.drawable.ic_default_art);
    }
}

From source file:be.ugent.zeus.hydra.util.audiostream.MusicService.java

@Override
public void onCreate() {
    Log.i(TAG, "debug: Creating service");

    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    if (mStartPlayingAfterRetrieve) {
        tryToGetAudioFocus();/*from ww w.j a  v a2 s  .  c om*/
        playStream();
    }

    // create the Audio Focus Helper, if the Audio Focus feature is available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8) {
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    } else {
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus
    }
    mDummyAlbumArt = BitmapFactory.decodeResource(getResources(), R.drawable.urgent_lockart);

    mMediaButtonReceiverComponent = new ComponentName(this, MusicIntentReceiver.class);
}

From source file:com.amrutpatil.makeanote.NotesActivity.java

@Override
public void onLoadFinished(Loader<List<Note>> loader, List<Note> data) {
    this.mNotes = data;
    //Retrieve the image from local storage/Google Drive/Dropbox in a separate thread
    Thread[] threads = new Thread[mNotes.size()];
    int threadCounter = 0;

    for (final Note aNote : mNotes) {
        //If the note is coming from Google Drive
        if (AppConstant.GOOGLE_DRIVE_SELECTION == aNote.getStorageSelection()) {
            GDUT.init(getApplicationContext());
            //Check if Google Drive is accessible and if the user account has been logged in successfully
            if (checkPlayServices() && checkUserAccount()) {
                GDActions.init(this, GDUT.AM.getActiveEmil());
                GDActions.connect(true);
            }// w w w  .  j  a v a  2  s. c  o  m

            threads[threadCounter] = new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        //Get the image file
                        ArrayList<GDActions.GF> gfs = GDActions.search(
                                AppSharedPreferences.getGoogleDriveResourceId(getApplicationContext()),
                                aNote.getImagePath(), GDUT.MIME_JPEG);

                        if (gfs.size() > 0) {
                            //Retrieve the file, convert it into Bitmap to display on the screen
                            byte[] imageBytes = GDActions.read(gfs.get(0).id, 0);

                            //Process the entire byte array and convert it into an image
                            Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                            aNote.setBitmap(bitmap);
                            mIsImageNotFound = false;
                            mNotesAdapter.setData(mNotes);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //Tell the Adapter that a graphic image has been obtained
                                    mNotesAdapter.notifyImageObtained();
                                }
                            });
                        } else {
                            aNote.setBitmap(
                                    BitmapFactory.decodeResource(getResources(), R.drawable.ic_loading));
                            mIsImageNotFound = true;
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } while (mIsImageNotFound);
                }
            });
            threads[threadCounter].start();
            threadCounter++;
        } else if (AppConstant.DROP_BOX_SELECTION == aNote.getStorageSelection()) {
            threads[threadCounter] = new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        Drawable drawable = getImageFromDropbox(mDropboxAPI,
                                AppSharedPreferences.getDropBoxUploadPath(getApplicationContext()),
                                aNote.getImagePath());
                        if (drawable != null) {
                            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                            aNote.setBitmap(bitmap);
                        }
                        if (!mIsImageNotFound) {
                            mNotesAdapter.setData(mNotes);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mNotesAdapter.notifyImageObtained();
                                }
                            });
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    } while (mIsImageNotFound);
                }
            });
            threads[threadCounter].start();
            threadCounter++;
        } else {
            aNote.setHasNoImage(true);
        }
    }
    mNotesAdapter.setData(mNotes); //Adapter has the latest copy of note
    changeNoItemTag();
}

From source file:com.allenxuan.xuanyihuang.littledownloadhelper.DownloadService.java

private Notification getNotification(String title, int progress, float fileSize, String fileSizeUnit) {
    String stringFileSize = String.format("%.2f", fileSize);
    String stringDownloadedFileSize = String.format("%.2f", fileSize * progress / 100);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    if (useNotificationTargetActivity && notificationTargetActivity != null) {
        Intent intent = new Intent(this, notificationTargetActivity);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pi);/* w ww .j a  v a 2 s. com*/
    }
    if (useNotificationSmallIcon) {
        builder.setSmallIcon(notificationSmallIconResId);
    }
    if (useNotificationLargeIcon) {
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), notificationLargeIconResId));
    }
    builder.setContentTitle(title);
    if (downloadProgressHintStyle == DownloadProgressHintStyle.FRACTION_STYLE) {
        builder.setContentText(stringDownloadedFileSize + fileSizeUnit + "/" + stringFileSize + fileSizeUnit);
        if (progress > 0)
            builder.setProgress(100, progress, false);
    } else if (downloadProgressHintStyle == DownloadProgressHintStyle.PERCENT_STYLE) {
        if (progress > 0) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
    } else if (downloadProgressHintStyle == DownloadProgressHintStyle.FRACTION_AND_PERCENT_TOGETHER) {
        StringBuffer stringBuffer = new StringBuffer(
                stringDownloadedFileSize + fileSizeUnit + "/" + stringFileSize + fileSizeUnit);
        if (progress > 0) {
            stringBuffer.append(" (" + progress + "%)");
            builder.setProgress(100, progress, false);
        }
        builder.setContentText(stringBuffer.toString());
    }
    builder.setWhen(notificationCreateTime);
    return builder.build();
}

From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java

private static void issueNotification(Context context, Set<String> addedMilestones,
        Set<String> removedMilestones, Map<String, int[]> changedProgresses) {
    String title = context.getString(R.string.notification_title);
    StringBuilder message = new StringBuilder();

    // Changed progresses
    for (String milestoneTitle : changedProgresses.keySet()) {
        int oldProgress = changedProgresses.get(milestoneTitle)[0];
        int newProgress = changedProgresses.get(milestoneTitle)[1];
        message.append("\n").append(String.format(context.getString(R.string.notific_msg_text_format),
                milestoneTitle, oldProgress, newProgress));
    }//w w w  .  ja v a 2  s.  c o  m

    // Added milestones
    for (String milestoneTitle : addedMilestones) {
        message.append("\n").append(context.getString(R.string.milestone_added_notification, milestoneTitle));
    }

    // Removed milestones
    for (String milestoneTitle : removedMilestones) {
        message.append("\n").append(context.getString(R.string.milestone_removed_notification, milestoneTitle));
    }

    // Remove first newline
    message.delete(0, 1);

    // Create PendingIntent
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean sound = pref.getBoolean(Constants.NOTIFICATION_SOUND_PREF, true);
    boolean vibrate = pref.getBoolean(Constants.NOTIFICATION_VIBRATE_PREF, true);
    boolean light = pref.getBoolean(Constants.NOTIFICATION_LIGHT_PREF, true);
    int defaults = 0;
    if (sound)
        defaults = defaults | Notification.DEFAULT_SOUND;
    if (vibrate)
        defaults = defaults | Notification.DEFAULT_VIBRATE;
    if (light)
        defaults = defaults | Notification.DEFAULT_LIGHTS;

    // Build the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(pendingIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setSmallIcon(R.mipmap.notification_small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setDefaults(defaults).setAutoCancel(true);

    // Issue the notification
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(PROGRESS_NOTIFICATION_ID, builder.build());
}