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.digi.android.wva.VehicleInfoService.java

/**
 * Depending on if the service is currently set as 'connected'
 * (check value of {@code isConnected} boolean), either call
 * {@link #startForeground(int, Notification)} to put up the
 * "service is running" notification, or call
 * {@link #stopForeground(boolean) stopForeground(true)} to remove the
 * notification (because the service isn't listening).
  */*from   w  ww. ja v  a2s .  c o  m*/
  * <p>This method is protected, rather than private, due to a bug between JaCoCo and
  * the Android build tools which causes the instrumented bytecode to be invalid when this
  * method is private:
  * http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode
  * </p>
 */
protected void showNotificationIfRunning() {
    // First, c
    WvaApplication app = (WvaApplication) getApplication();
    if (app != null && app.isTesting())
        return;

    if (isConnected) {
        NotificationCompat.Builder builder;
        builder = new NotificationCompat.Builder(getApplicationContext());
        PendingIntent contentIntent;
        Intent intent = new Intent(VehicleInfoService.this, DashboardActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        contentIntent = PendingIntent.getActivity(VehicleInfoService.this, 0, intent, 0);
        builder.setContentTitle("Digi WVA Service")
                .setContentText("Connected to " + (TextUtils.isEmpty(connectIp) ? "(null)" : connectIp))
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setSmallIcon(R.drawable.notif_small).setOngoing(true).setContentIntent(contentIntent);

        startForeground(NOTIF_ID, builder.build());
    } else {
        try {
            stopForeground(true);
        } catch (Exception e) {
            // Might happen if startForeground not called before
            e.printStackTrace();
        }
    }
}

From source file:com.star.printer.StarPrinter.java

/**
 * This function is used to print a java bitmap directly to a portable
 * printer.// www.  j ava  2s.c o m
 * 
 * @param context
 *            Activity for displaying messages to the user
 * @param portName
 *            Port name to use for communication. This should be
 *            (TCP:<IPAddress> or BT:<Device pair name>)
 * @param portSettings
 *            Should be mini, the port settings mini is used for portable
 *            printers
 * @param res
 *            The resources object containing the image data
 * @param source
 *            The resource id of the image data
 * @param maxWidth
 *            The maximum width of the image to print. This is usually the
 *            page width of the printer. If the image exceeds the maximum
 *            width then the image is scaled down. The ratio is maintained.
 */
public static void PrintBitmapImage(Context context, String portName, String portSettings, Resources res,
        int source, int maxWidth, boolean compressionEnable, boolean pageModeEnable) {
    ArrayList<byte[]> commands = new ArrayList<byte[]>();

    Bitmap bm = BitmapFactory.decodeResource(res, source);
    StarBitmap starbitmap = new StarBitmap(bm, false, maxWidth);

    try {

        commands.add(starbitmap.getImageEscPosDataForPrinting(compressionEnable, pageModeEnable));

        sendCommand(context, portName, portSettings, commands);
    } catch (StarIOPortException e) {
        Builder dialog = new AlertDialog.Builder(context);
        dialog.setNegativeButton("Ok", null);
        AlertDialog alert = dialog.create();
        alert.setTitle("Failure");
        alert.setMessage(e.getMessage());
        alert.setCancelable(false);
        alert.show();
    }
}

From source file:co.shunya.gita.player.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);

    // 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/*from   w w  w . ja  va  2  s.c  om*/
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus

    mDummyAlbumArt = BitmapFactory.decodeResource(getResources(), R.drawable.krishnanarayana);

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

    BusProvider.getMediaEventBus().register(this);

}

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

private void performProbe(final Intent intent) {
    Intent newIntent = new Intent();
    newIntent.setAction(ProgressFragment.ORG_BROADCAST);
    newIntent.putExtra(ProgressFragment.ORG_BROADCAST, ProgressFragment.TALKING_TO_ISP);
    sendBroadcast(newIntent);//from w  w w  .j  a v  a  2  s  .  com

    //If this is user submitted send it up for further research
    if (intent.getBooleanExtra("local", false)) {
        new Thread() {
            public void run() {
                try {
                    api.submitURL(intent.getStringExtra("url"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    mBuilder.setStyle(new NotificationCompat.InboxStyle()
            .setBigContentTitle(getString(R.string.notifTitle) + " - " + getString(R.string.notifURLRecv))
            .addLine(getString(R.string.notifNewURL)).addLine(getString(R.string.notifSanityCheck))
            .setSummaryText(Integer.toString(checkedCount) + " " + getString(R.string.notifChecked) + " / "
                    + Integer.toString(censoredCount) + " " + getString(R.string.notifPossBlock)))
            .setSmallIcon(R.drawable.ic_stat_in_progress)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_ooni_large))
            .setPriority(Notification.PRIORITY_MAX)
            .setTicker(getString(R.string.notifTitle) + " - " + getString(R.string.notifURLRecv))
            .setAutoCancel(false);

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

    new Thread(new Runnable() {
        @Override
        public void run() {
            String url = intent.getStringExtra("url");
            String hash = intent.getStringExtra("hash");

            //Pair<Boolean,Integer> wasCensored;
            CensorPayload censorPayload;

            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

            mBuilder.setStyle(new NotificationCompat.InboxStyle()
                    .setBigContentTitle(
                            getString(R.string.notifTitle) + " - " + getString(R.string.notifCheckURL))
                    .addLine(getString(R.string.notifStartAt) + " " + currentDateTimeString)
                    .addLine(getString(R.string.notifCheckURL) + ".....").addLine("MD5: " + hash)
                    .setSummaryText(Integer.toString(checkedCount) + " " + getString(R.string.notifChecked)
                            + " / " + Integer.toString(censoredCount) + " "
                            + getString(R.string.notifPossBlock)));
            mBuilder.setProgress(2, 1, true);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());

            try {
                if (null == url)
                    throw new NullPointerException();

                //Do the actual check
                censorPayload = checkURL(url);

                //We're complete - update the time
                currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

                //Update our local stats
                setCounts(censorPayload.wasCensored());

                censorPayload.MD5 = hash;

                Intent ORGCensorIntent = new Intent();
                ORGCensorIntent.setAction(ProgressFragment.ORG_BROADCAST);
                ORGCensorIntent.putExtra("url", url);
                ORGCensorIntent.putExtra("hash", hash);
                ORGCensorIntent.putExtra("date", currentDateTimeString);

                if (censorPayload.wasCensored()) {
                    ORGCensorIntent.putExtra(ProgressFragment.ORG_BROADCAST, ProgressFragment.BLOCKED);
                    ORGCensorIntent.putExtra(ResultsGrid.INTENT_FILTER, LocalCache.RESULT_BLOCKED);

                    mBuilder.setTicker(getString(R.string.notifFoundBlock));
                    mBuilder.setStyle(new NotificationCompat.InboxStyle()
                            .setBigContentTitle(
                                    getString(R.string.notifTitle) + " - " + getString(R.string.notifWaiting))
                            .addLine(getString(R.string.notifLastChk) + ": " + currentDateTimeString)
                            .addLine(getString(R.string.notifLastURLBlocked))
                            .addLine("MD5: " + intent.getStringExtra("hash"))
                            .setSummaryText(Integer.toString(checkedCount) + " "
                                    + getString(R.string.notifChecked) + " / " + Integer.toString(censoredCount)
                                    + " " + getString(R.string.notifPossBlock))

                    );
                    mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),
                            R.drawable.ic_ooni_large_censored));
                } else {

                    ORGCensorIntent.putExtra(ProgressFragment.ORG_BROADCAST, ProgressFragment.OK);
                    ORGCensorIntent.putExtra(ResultsGrid.INTENT_FILTER, LocalCache.RESULT_OK);

                    mBuilder.setTicker(
                            getString(R.string.notifTitle) + " - " + getString(R.string.notifLastChkNotBlock));
                    mBuilder.setStyle(new NotificationCompat.InboxStyle()
                            .setBigContentTitle(
                                    getString(R.string.notifTitle) + " - " + getString(R.string.notifWaiting))
                            .addLine(getString(R.string.notifLastChk) + ": " + currentDateTimeString)
                            .addLine(getString(R.string.notifLastChkNotBlock))
                            .setSummaryText(Integer.toString(checkedCount) + " "
                                    + getString(R.string.notifChecked) + " / " + Integer.toString(censoredCount)
                                    + " " + getString(R.string.notifPossBlock)));
                }

                sendBroadcast(ORGCensorIntent);
            } catch (Exception e) {
                e.printStackTrace();

                //We're complete - update the time
                currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

                mBuilder.setStyle(new NotificationCompat.InboxStyle()
                        .setBigContentTitle(
                                getString(R.string.notifTitle) + " - " + getString(R.string.notifError))
                        .addLine(getString(R.string.notifLastChk) + ": " + currentDateTimeString)
                        .addLine(getString(R.string.notifException))
                        .setSummaryText(Integer.toString(checkedCount) + " " + getString(R.string.notifChecked)
                                + " / " + Integer.toString(censoredCount) + " "
                                + getString(R.string.notifPossBlock)));

                censorPayload = null;

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

            mBuilder.setProgress(0, 0, false);
            mBuilder.setSmallIcon(R.drawable.ic_stat_waiting);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());

            //Send the details back regardless (will chew DB space but will give a clearer picture)
            //api.notifyBackEnd(url,"",wasCensored, intent.getStringExtra("isp"), intent.getStringExtra("sim"));
            api.notifyBackEnd(censorPayload);

            /*if(sendtoORG)
                notifyOONIDirectly(url,wasCensored, intent.getStringExtra("isp"), intent.getStringExtra("sim"));
            */

            onProbeFinish();
        }
    }).start();
}

From source file:com.careme.apvereda.careme.AccumulatorService.java

private void shownot(String s) {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_notifications);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.mipmap.ic_notsmall).setLargeIcon(bitmap).setContentTitle("Cuidado!")
            .setContentText(s).setVibrate(new long[] { 100, 250, 100, 500 });
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    int mNotificationId = 001;
    NotificationManager mNotifyMgr = (NotificationManager) getApplicationContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());
}

From source file:dev.memento.MainActivity.java

/** Called when the activity is first created. */
@Override/*  w ww  .  j  av a  2s .  c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mUserPressedBack = false;

    setContentView(R.layout.activity_main);

    mUserAgent = getApplicationContext().getText(R.string.user_agent).toString();

    mWebHistory = new Stack<ExWebHistoryItem>();

    // Set the date and time format
    SimpleDateTime.mDateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
    SimpleDateTime.mTimeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());

    // Holds all the timemaps for the web page being viewed
    mTimeMaps = new HashSet<TimeMap>();

    // Set the current date
    mToday = new SimpleDateTime();

    mCurrentUrl = getApplicationContext().getText(R.string.homepage).toString();
    mOriginalUrl = mCurrentUrl;

    mDateChosen = mToday;
    mDateDisplayed = mToday;

    mMementos = new MementoList();

    // Add some favicons of web archives used by proxy server
    mFavicons = new HashMap<String, Bitmap>();
    mFavicons.put("ia", BitmapFactory.decodeResource(getResources(), R.drawable.ia_favicon));
    mFavicons.put("webcite", BitmapFactory.decodeResource(getResources(), R.drawable.webcite_favicon));
    mFavicons.put("national-archives",
            BitmapFactory.decodeResource(getResources(), R.drawable.national_archives_favicon));

    initUI();
}

From source file:com.example.main.BandWViewPagerActivity.java

private void getmArrays(String decode) {
    // TODO Auto-generated method stub
    try {//from w ww.  ja  v a  2s .  c om
        GlobalID globalID = (GlobalID) getApplication();
        JSONArray jsonArray = new JSONArray(decode);
        if (jsonArray.length() == 0) {
            return;
        } else {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                BandWEntity entity = new BandWEntity(Boolean.valueOf(jsonObject.optString("list_type")),
                        jsonObject.optString("Id"), jsonObject.optString("Title"),
                        jsonObject.optString("Typeid"),
                        Html.fromHtml(jsonObject.optString("Detail")).toString(), jsonObject.optString("Pic"),
                        jsonObject.optString("Time"));

                if (!entity.getList_type()) {
                    String pic = entity.getPicName();
                    if (log)
                        Log.v(i + " pic: ", pic);
                    Bitmap bit = FuntionUtil
                            .downloadPic("http://" + globalID.getDBurl() + "/admin/images/" + pic);
                    if (bit != null) {
                        entity.setPic(bit);
                    } else {
                        Bitmap good = BitmapFactory.decodeResource(getResources(), R.drawable.weather_preview);
                        entity.setPic(good);
                    }
                }

                //               mArrays.add(entity);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = entity;
                add_handler.sendMessage(msg);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }
}

From source file:br.org.funcate.dynamicforms.views.GPictureView.java

public void refresh(final Context context) throws Exception {

    imageLayout.removeAllViewsInLayout();
    int increaseTime = 0;// using on runnable

    if (_pictures != null && _pictures.size() > 0) {

        Set<String> imageKeys = _pictures.keySet();
        for (final String imageId : imageKeys) {

            if (!_pictures.containsKey(imageId)) {
                // TODO: Here, write a log in logfile
                continue;
            } else {
                Map<String, String> imagePaths = _pictures.get(imageId);
                final String imagePath = imagePaths.get("thumbnail");
                final ProgressBar pgBar = getProgressBar(context);
                imageLayout.addView(pgBar);
                increaseTime++;/*from   w  w w. jav  a 2 s.  com*/

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        /*
                                                    byte[] image = ImageUtilities.getImageFromPath(imagePath, 2);
                                                    if (image != null && image.length > 0) {
                        Bitmap imageBitmap = ImageUtilities.getBitmapFromBlob(image);
                        try {
                            image = null;
                        } catch (Throwable t) {
                            t.printStackTrace();
                            getDefaultBitmap();
                            return;
                        }
                                
                        Bitmap thumbnail = ImageUtilities.makeThumbnail(imageBitmap);
                        if (imageBitmap.isRecycled()) imageBitmap.recycle();
                        */
                        if (imagePath != null && !imagePath.isEmpty() && (new File(imagePath)).exists()) {
                            pgBar.setVisibility(View.GONE);
                            imageLayout.addView(getImageView(context, imagePath, imageId));
                            imageLayout.invalidate();
                            //if (thumbnail.isRecycled()) thumbnail.recycle();
                        } else {
                            getDefaultBitmap();
                        }
                    }

                    public void getDefaultBitmap() {
                        pgBar.setVisibility(View.GONE);
                        Bitmap bitmapError = BitmapFactory.decodeResource(getResources(),
                                R.drawable.ic_stat_action_highlight_remove);
                        imageLayout.addView(getImageView(context, bitmapError, imageId));
                        imageLayout.invalidate();
                        // if (bitmapError.isRecycled()) bitmapError.recycle();
                    }
                }, increaseTime * 1000 + 1000);
            }
        }
    }
    if (newImagesFromCamera != null && newImagesFromCamera.size() > 0) {
        Set<String> imageKeys = newImagesFromCamera.keySet();
        for (final String imageId : imageKeys) {

            final String imagePath = newImagesFromCamera.get(imageId);
            final ProgressBar pgBar = getProgressBar(context);
            imageLayout.addView(pgBar);
            increaseTime++;

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    try {

                        if (imagePath != null && !imagePath.isEmpty() && (new File(imagePath)).exists()) {

                            pgBar.setVisibility(View.GONE);
                            imageLayout.addView(getImageView(context, imagePath, imageId));
                            imageLayout.invalidate();

                            /*
                            if (!ImageUtilities.resampleImage(imagePath)) {
                            getDefaultBitmap();
                            return;
                            }
                            byte[] image = ImageUtilities.getImageFromPath(imagePath, 2);
                            if (image != null) {
                            Bitmap imageBitmap = ImageUtilities.getBitmapFromBlob(image);
                            image = null;
                            Bitmap thumbnail = ImageUtilities.makeThumbnail(imageBitmap);
                            imageBitmap = null;
                            pgBar.setVisibility(View.GONE);
                            imageLayout.addView(getImageView(context, thumbnail, imageId));
                            thumbnail = null;
                            imageLayout.invalidate();
                            } else {
                            getDefaultBitmap();
                            }
                            */
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                        getDefaultBitmap();
                    }
                }

                public void getDefaultBitmap() {
                    pgBar.setVisibility(View.GONE);
                    Bitmap bitmapError = BitmapFactory.decodeResource(getResources(),
                            R.drawable.ic_stat_action_highlight_remove);
                    imageLayout.addView(getImageView(context, bitmapError, imageId));
                    imageLayout.invalidate();
                }
            }, increaseTime * 1000 + 1000);

            if (!addedIdsToImageViews.containsValue(imagePath))
                addedIdsToImageViews.put(imageId, imagePath);
        }
    }

    imageLayout.invalidate();

}

From source file:com.example.main.ViewPagerActivity.java

private void getTalkDataArrays(String decode) {
    // TODO Auto-generated method stub
    try {/*from w ww.j a  va  2 s  . c o  m*/
        JSONArray jsonArray = new JSONArray(decode);
        if (jsonArray.length() == 0) {
            return;
        } else {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                TalkEntity entity = new TalkEntity(Boolean.valueOf(jsonObject.optString("isMsg")),
                        Boolean.valueOf(jsonObject.optString("isSend"))

                        , Html.fromHtml(jsonObject.optString("detail")).toString(),
                        jsonObject.optString("PostTime"), jsonObject.optString("ark_id"),
                        jsonObject.optString("send_user_id"), jsonObject.optString("msg_id"));

                entity.setState(Integer.valueOf(jsonObject.optString("state")));

                LogHelper.trace(jsonObject.optString("detail"));
                LogHelper.trace(Html.fromHtml(jsonObject.optString("detail")).toString());

                if (jsonObject.optString("isMsg").equals("false")) {
                    String pic = jsonObject.optString("detail");
                    GlobalID globalID = ((GlobalID) getApplication());
                    Bitmap bit = FuntionUtil
                            .downloadPic("http://" + globalID.getDBurl() + "/user/images" + pic);
                    if (bit != null) {
                        entity.setImage_picture(bit);
                    } else {
                        Bitmap default_Img = BitmapFactory.decodeResource(getResources(),
                                R.drawable.ic_launcher);
                        entity.setImage_picture(default_Img);
                    }
                }

                //               TalkDataArrays.add(entity);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = entity;
                add_handler.sendMessage(msg);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }
}

From source file:co.ldln.android.MapFragment.java

private void insertMarker(double lat, double lon, String title, String description, int icon_id,
        boolean recenterMap) {
    // Prepare the features needed for constructing the marker
    Bitmap icon = BitmapFactory.decodeResource(getActivity().getResources(), icon_id);
    LDLNMarkerAttributes properties = new LDLNMarkerAttributes(title, description);

    // Create the marker and add it to the array to be added to the map
    ScreenMarker marker = new LDLNScreenMarker(lat, lon, 45, icon, properties);

    // Add your marker to the map controller.
    MarkerInfo markerInfo = new MarkerInfo();
    ComponentObject markersComponentObject = mapControl.addScreenMarker(marker, markerInfo,
            MaplyBaseController.ThreadMode.ThreadAny);

    // Keep list of objects for removal.
    // ComponentObject is your handle to the marker in the map controller.
    // You can use this to enable, disable, and remove your marker from the map.
    markers.add(markersComponentObject);

    // Center the map if asked to
    if (recenterMap) {
        Point2d centerPt = Point2d.FromDegrees(lon, lat);
        mapControl.animatePositionGeo(centerPt.getX(), centerPt.getY(), mapControl.getPositionGeo().getZ(),
                0.6);/*from w w  w. j a  va2  s. co  m*/
    }
}