Example usage for android.graphics Bitmap createScaledBitmap

List of usage examples for android.graphics Bitmap createScaledBitmap

Introduction

In this page you can find the example usage for android.graphics Bitmap createScaledBitmap.

Prototype

public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, boolean filter) 

Source Link

Document

Creates a new bitmap, scaled from an existing bitmap, when possible.

Usage

From source file:im.vector.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs/*w w  w.j a v a 2  s  .c  o  m*/
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    cursor.close();
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mConsoleMessageListFragment.uploadMediaContent(fMediaUrl, fMimeType,
                                                fFilename);
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

From source file:dev.memento.MainActivity.java

private BitmapDrawable resizeImage(BitmapDrawable image, int size) {
    Bitmap b = image.getBitmap();//from   ww  w .  j av a 2  s.co m
    if (b.getWidth() < size) {
        Bitmap bitmapResized = Bitmap.createScaledBitmap(b, size, size, false);
        return new BitmapDrawable(this.getResources(), bitmapResized);
    } else {
        // Don't worry about resizing if large enough
        return image;
    }
}

From source file:com.chen.mail.utils.NotificationUtils.java

private static Bitmap getContactIcon(final Context context, final String displayName,
        final String senderAddress, final Folder folder) {
    if (senderAddress == null) {
        return null;
    }//from   w  ww .  j  a  v  a  2s  .co m

    Bitmap icon = null;

    final List<Long> contactIds = findContacts(context, Arrays.asList(new String[] { senderAddress }));

    // Get the ideal size for this icon.
    final Resources res = context.getResources();
    final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
    final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);

    if (contactIds != null) {
        for (final long id : contactIds) {
            final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
            final Uri photoUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
            final Cursor cursor = context.getContentResolver().query(photoUri, new String[] { Photo.PHOTO },
                    null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        final byte[] data = cursor.getBlob(0);
                        if (data != null) {
                            icon = BitmapFactory.decodeStream(new ByteArrayInputStream(data));
                            if (icon != null && icon.getHeight() < idealIconHeight) {
                                // We should scale this image to fit the intended size
                                icon = Bitmap.createScaledBitmap(icon, idealIconWidth, idealIconHeight, true);
                            }
                            if (icon != null) {
                                break;
                            }
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }
    }

    if (icon == null) {
        // Make a colorful tile!
        final ImageCanvas.Dimensions dimensions = new ImageCanvas.Dimensions(idealIconWidth, idealIconHeight,
                ImageCanvas.Dimensions.SCALE_ONE);

        icon = new LetterTileProvider(context).getLetterTile(dimensions, displayName, senderAddress);
    }

    if (icon == null) {
        // Icon should be the default mail icon.
        icon = getDefaultNotificationIcon(context, folder, false /* single new message */);
    }
    return icon;
}

From source file:com.indeema.mail.utils.NotificationUtils.java

private static Bitmap getContactIcon(final Context context, final String displayName,
        final String senderAddress, final Folder folder) {
    if (senderAddress == null) {
        return null;
    }/*from  w w  w . ja  va  2 s.c  o  m*/

    Bitmap icon = null;

    final List<Long> contactIds = findContacts(context, Arrays.asList(new String[] { senderAddress }));

    // Get the ideal size for this icon.
    final Resources res = context.getResources();
    final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
    final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);

    if (contactIds != null) {
        for (final long id : contactIds) {
            final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
            final Uri photoUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
            final Cursor cursor = context.getContentResolver().query(photoUri, new String[] { Photo.PHOTO },
                    null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        final byte[] data = cursor.getBlob(0);
                        if (data != null) {
                            icon = BitmapFactory.decodeStream(new ByteArrayInputStream(data));
                            if (icon != null && icon.getHeight() < idealIconHeight) {
                                // We should scale this image to fit the intended size
                                icon = Bitmap.createScaledBitmap(icon, idealIconWidth, idealIconHeight, true);
                            }
                            if (icon != null) {
                                break;
                            }
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }
    }

    if (icon == null) {
        // Make a colorful tile!
        final Dimensions dimensions = new Dimensions(idealIconWidth, idealIconHeight, Dimensions.SCALE_ONE);

        icon = new LetterTileProvider(context).getLetterTile(dimensions, displayName, senderAddress);
    }

    if (icon == null) {
        // Icon should be the default mail icon.
        icon = getDefaultNotificationIcon(context, folder, false /* single new message */);
    }
    return icon;
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void initObstaclesAndPreLoad(int[] resources, int stride, TreeMap<Integer, Bitmap> map,
        ArrayList<Integer> list) {
    initObstacles(resources, stride, list);
    // Load the bitmaps for the first 20 obstacles.
    for (int i = 0; i < 20; i++) {
        int obstacle = list.get(i);
        for (int j = (obstacle * stride); j < ((obstacle + 1) * stride); j++) {
            // Check just in case something is wonky
            if (j < resources.length) {
                int id = resources[j];
                if (id != -1) {
                    // Only need to load it once...
                    if (!map.containsKey(id)) {
                        Bitmap bmp = BitmapFactory.decodeResource(getResources(), id);
                        if ((mScaleX != 1.0f) || (mScaleY != 1.0f)) {
                            Bitmap tmp = Bitmap.createScaledBitmap(bmp,
                                    (int) ((float) bmp.getWidth() * mScaleX),
                                    (int) ((float) bmp.getHeight() * mScaleY), false);
                            if (tmp != bmp) {
                                bmp.recycle();
                            }/*from w  w w.ja v  a2s.c o m*/
                            map.put(id, tmp);
                        } else {
                            map.put(id, bmp);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.lifehackinnovations.siteaudit.FloorPlanActivity.java

public void save() {
    try {//from  ww w  .ja v  a  2  s  .c  om
        runOnUiThread(new Runnable() {
            public void run() {
                view.addvaluestotabstable();
                view.addvaluestobom();
                if (u.isbluestacks()) {
                    //Tabs1.bluestacksimagequalitydialog(getBaseContext());
                }
            }
        });

        if (ACTION == ACTION_SHOWLAYERS) {
            ACTION = ACTION_DONOTHING;
        }

        Log.d("MULTILEVEL checked in save", String.valueOf(MULTILEVEL));
        //            if(!MULTILEVEL){
        //               Canvas canvascopy = new Canvas();
        //               Bitmap canvasbitmap=resizedbitmaponmemorycheck();
        //               canvascopy.setBitmap(canvasbitmap);
        //
        //               view.DONTSCALEORTRANSLATE = true;
        //               view.CanvasChanges(canvascopy);
        //               view.DONTSCALEORTRANSLATE = false;
        //
        //               File file = new File(Tabs1.OutputFloorPlanLocation[FloorPlanView.fp]);
        //               file.mkdirs();
        //               if (file.exists())
        //                  file.delete();
        //
        //               FileOutputStream fos = new FileOutputStream(
        //                     new File(Tabs1.OutputFloorPlanLocation[FloorPlanView.fp]));
        //
        //               canvasbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        //               //canvasbitmap.recycle();
        //               try {
        //                  Log.d("trying outputstream flush and close","true");
        //                  fos.flush();
        //                  fos.close();
        //                  fos = null;
        //               } catch (IOException e) {
        //                  // TODO Auto-generated catch block
        //                  e.printStackTrace();
        //               }
        //            }else{

        //recycling original canvas

        Log.d("floorplancount", u.s(floorplancount));
        for (int x = 0; x < floorplancount; x++) {
            Log.d("floorplan count", u.s(x));
            FloorPlanView.fp = x;
            //                  view.originalbitmap = BitmapFactory.decodeFile(Tabs1.InputFloorPlanLocation[x]);
            //                  Log.d("inputfloorplan path",Tabs1.InputFloorPlanLocation[x].toString());
            //                  view.bm = view.originalbitmap;
            //                  view.bitheight = view.bm.getHeight();
            //                  view.bitwidth = view.bm.getWidth();
            view.invalidate();

            Canvas canvascopy = new Canvas();
            Bitmap canvasbitmap = resizedbitmaponmemorycheck();
            canvascopy.setBitmap(canvasbitmap);

            view.DONTSCALEORTRANSLATE = true;
            view.CanvasChanges(canvascopy);
            view.DONTSCALEORTRANSLATE = false;

            String newoutputfilestring = Tabs1.floorplanstrings.get(x).replace(Tabs1.inputfloorplandirectory,
                    Tabs1.outputfloorplandirectory);

            File file = new File(newoutputfilestring);
            file.mkdirs();
            if (file.exists())
                file.delete();

            FileOutputStream fos = new FileOutputStream(new File(newoutputfilestring));

            Log.d("outputfloorplan path", newoutputfilestring);
            canvasbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            //canvasbitmap.recycle();
            try {
                Log.d("trying outputstream flush and close", "true");
                fos.flush();
                fos.close();
                fos = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = Tabs1.FLOORPLANPICTURESIZE;
            Bitmap bm = BitmapFactory.decodeFile(newoutputfilestring, o);

            double calcheight = (double) Tabs1.screenheight
                    * (double) Tabs1.FLOORPLANPICTUREDISPLAYPERCENTOFSCREEN / (double) 100;
            double calcwidth = (double) bm.getWidth() / (double) bm.getHeight() * (double) calcheight;

            int height = (int) calcheight;
            int width = (int) calcwidth;

            Bitmap resizedbitmap = null;

            outputfloorplanthumbnail = Bitmap.createScaledBitmap(bm, width, height, true);
            bm.recycle();
            canvasbitmap.recycle();

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //writeexcel();
    //rewritewholedb();
    System.out.println("database after write db");
    try {
        Tabs1.db.showfulldblog(dbtablename);
    } catch (Throwable e) {

    }
    FINALBITMAPSCALE = 1;
}

From source file:org.cryptsecure.Utility.java

/**
 * Get a resized version of a bitmap image.
 * /*from  www  .  j av  a  2s.c  o m*/
 * @param bitmap
 *            the bitmap
 * @param maxWidth
 *            the max width
 * @param maxHeight
 *            the max height
 * @return the resized image
 */
public static Bitmap getResizedImage(Bitmap bitmap, int maxWidth, int maxHeight, boolean deleteSource,
        boolean clipped) {
    int bitmapWidth = bitmap.getWidth();
    int bitmapHeight = bitmap.getHeight();
    int newWidth = bitmapWidth;
    int newHeight = bitmapHeight;

    Log.d("communicator", "RESIZE: maxWidth=" + maxWidth + ", maxHeight=" + maxHeight);
    Log.d("communicator", "RESIZE: bmpW=" + bitmapWidth + ", bmpH=" + bitmapHeight);

    boolean landscape = bitmapWidth > bitmapHeight;
    if (clipped) {
        landscape = !landscape;
    }

    if (landscape) {
        // Log.d("communicator", "RESIZE Landscape: bitmapWidth="
        // + bitmapWidth + " >? " + maxWidth + "=maxWidth");
        // Landscape
        // if (bitmapWidth > maxWidth) {
        float scale = ((float) bitmapWidth) / ((float) maxWidth);
        // Log.d("communicator", "RESIZE: (1) scale=" + scale);
        newWidth = maxWidth;
        newHeight = (int) ((float) bitmapHeight / scale);
        // } else if (bitmapHeight > maxHeight) {
        // float scale = ((float) bitmapHeight) / ((float) maxHeight);
        // // Log.d("communicator", "RESIZE: (2) scale=" + scale);
        // newHeight = maxHeight;
        // newWidth = (int) ((float) bitmapWidth / scale);
        // }

    } else {
        // Log.d("communicator", "RESIZE Portrait: bitmapHeight="
        // + bitmapHeight + " >? " + maxHeight + "=maxHeight");
        // Portrait
        // if (bitmapHeight > maxHeight) {
        float scale = ((float) bitmapHeight) / ((float) maxHeight);
        // Log.d("communicator", "RESIZE: (3) scale=" + scale);
        newHeight = maxHeight;
        newWidth = (int) ((float) bitmapWidth / scale);
        // } else if (bitmapWidth > maxWidth) {
        // float scale = ((float) bitmapWidth) / ((float) maxWidth);
        // // Log.d("communicator", "RESIZE: (4) scale=" + scale);
        // newWidth = maxWidth;
        // newHeight = (int) ((float) bitmapHeight / scale);
        // }
    }
    Log.d("communicator", "RESIZE RESULT: newWidth=" + newWidth + ", " + newHeight + "=newHeight");
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

    if (deleteSource) {
        bitmap.recycle();
        System.gc();
    }

    if (clipped) {
        Bitmap clippedBitmap = Bitmap.createBitmap(scaledBitmap, ((newWidth - maxWidth) / 2),
                ((newHeight - maxHeight) / 2), maxWidth, maxHeight);

        Log.d("communicator",
                "RESIZE RESULT2: width=" + clippedBitmap.getWidth() + ", height=" + clippedBitmap.getHeight());

        scaledBitmap.recycle();
        System.gc();
        return clippedBitmap;
    }

    return scaledBitmap;
}

From source file:foam.starwisp.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {

    String type = "";
    Integer tid = 0;//from ww  w  . ja v a2  s  .com
    String token = "";

    try {

        type = arr.getString(0);
        tid = arr.getInt(1);
        token = arr.getString(2);

    } catch (JSONException e) {
        Log.e("starwisp",
                "Error parsing update arguments for " + ctxname + " " + arr.toString() + e.toString());
    }

    final Integer id = tid;

    //Log.i("starwisp", "Update: "+type+" "+id+" "+token);

    try {

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            LinearLayout linearLayout = (LinearLayout) msg.getView();
            View child = linearLayout.getChildAt(0);
            TextView messageTextView = (TextView) child;
            messageTextView.setTextSize(arr.getInt(4));
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("soundfile-start-recording")) {
            String filename = arr.getString(3);
            m_SoundManager.StartRecording(filename);
        }
        if (token.equals("soundfile-stop-recording")) {
            m_SoundManager.StopRecording();
        }
        if (token.equals("soundfile-start-playback")) {
            String filename = arr.getString(3);
            m_SoundManager.StartPlaying(filename);
        }
        if (token.equals("soundfile-stop-playback")) {
            m_SoundManager.StopPlaying();
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(  R.animator.fragment_slide_left_enter,
            //             R.animator.fragment_slide_right_exit);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("view")) {
            //ctx.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse()));

            File f = new File(arr.getString(3));
            Uri fileUri = Uri.fromFile(f);

            Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(arr.getString(3));
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            myIntent.setDataAndType(fileUri, mimetype);
            ctx.startActivity(myIntent);
            return;
        }

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this, arr.getInt(5), arr.getInt(6));
            return;
        }

        if (token.equals("sensors-get")) {
            final String name = arr.getString(3);
            if (m_SensorHandler == null) {
                m_SensorHandler = new SensorHandler((StarwispActivity) ctx, this);
            }
            m_SensorHandler.GetSensors((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("sensors-start")) {
            final String name = arr.getString(3);
            final JSONArray requested_json = arr.getJSONArray(5);
            ArrayList<Integer> requested = new ArrayList<Integer>();

            try {
                for (int i = 0; i < requested_json.length(); i++) {
                    requested.add(requested_json.getInt(i));
                }
            } catch (JSONException e) {
                Log.e("starwisp", "Error parsing data in sensors start " + e.toString());
            }

            // start it up...
            if (m_SensorHandler == null) {
                m_SensorHandler = new SensorHandler((StarwispActivity) ctx, this);
            }
            m_SensorHandler.StartSensors((StarwispActivity) ctx, name, this, requested);
            return;
        }

        if (token.equals("sensors-stop")) {
            if (m_SensorHandler != null) {
                m_SensorHandler.StopSensors();
            }
            return;
        }

        if (token.equals("walk-draggable")) {
            final String name = arr.getString(3);
            int iid = arr.getInt(5);
            DialogCallback(ctx, ctxname, name, WalkDraggable(ctx, name, ctxname, iid).replace("\\", ""));
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            Log.i("starwisp", "http-request called");
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", "", name);
            }
            return;
        }

        if (token.equals("http-post")) {
            Log.i("starwisp", "http-post called");
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                final String data = arr.getString(6);
                m_NetworkManager.StartRequestThread(url, "post", data, name);
            }
            return;
        }

        if (token.equals("http-upload")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http ul request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "upload", "", filename);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", "", filename);
            }
            return;
        }

        if (token.equals("take-photo")) {
            photo(ctx, arr.getString(3), arr.getInt(4));
        }

        if (token.equals("bluetooth")) {
            final String name = arr.getString(3);
            m_Bluetooth.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("bluetooth-send")) {
            m_Bluetooth.Write(arr.getString(3));
        }

        if (token.equals("process-image-in-place")) {
            BitmapCache.ProcessInPlace(arr.getString(3));
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {
            final String name = arr.getString(3);
            final String msg = arr.getString(5);
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };
            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();
            return;
        }

        if (token.equals("ok-dialog")) {
            final String name = arr.getString(3);
            final String msg = arr.getString(5);
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };
            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Ok", dialogClickListener).show();
            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        if (id == 0) {
            Log.i("starwisp", "Zero ID, aborting...");
            return;
        }

        // now try and find the widget
        final View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // only tested on spinners
        if (token.equals("disabled")) {
            vv.setAlpha(0.3f);
            //vv.getSelectedView().setEnabled(false);
            vv.setEnabled(false);
            return;
        }

        if (token.equals("enabled")) {
            vv.setAlpha(1.0f);
            //vv.getSelectedView().setEnabled(true);
            vv.setEnabled(true);
            return;
        }

        if (token.equals("animate")) {
            JSONArray trans = arr.getJSONArray(3);

            final TranslateAnimation animation = new TranslateAnimation(getPixelsFromDp(ctx, trans.getInt(0)),
                    getPixelsFromDp(ctx, trans.getInt(1)), getPixelsFromDp(ctx, trans.getInt(2)),
                    getPixelsFromDp(ctx, trans.getInt(3)));
            animation.setDuration(1000);
            animation.setFillAfter(false);
            animation.setInterpolator(new AnticipateOvershootInterpolator(1.0f));
            animation.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                    vv.clearAnimation();
                    Log.i("starwisp", "animation end");
                    ((ViewManager) vv.getParent()).removeView(vv);

                    //LayoutParams lp = new LayoutParams(imageView.getWidth(), imageView.getHeight());
                    //lp.setMargins(50, 100, 0, 0);
                    //imageView.setLayoutParams(lp);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                    Log.i("starwisp", "animation start");
                }

            });

            vv.startAnimation(animation);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            Log.i("starwisp", "set-enabled called...");
            vv.setEnabled(arr.getInt(3) == 1);
            vv.setClickable(arr.getInt(3) == 1);
            if (vv.getBackground() != null) {
                if (arr.getInt(3) == 0) {
                    //vv.setBackgroundColor(0x00000000);
                    vv.getBackground().setColorFilter(0x20000000, PorterDuff.Mode.MULTIPLY);
                } else {
                    vv.getBackground().setColorFilter(null);
                }
            }
            return;
        }

        if (token.equals("background-colour")) {
            JSONArray col = arr.getJSONArray(3);

            if (type.equals("linear-layout")) {
                vv.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            } else {
                //vv.setBackgroundColor();
                vv.getBackground().setColorFilter(
                        Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)),
                        PorterDuff.Mode.MULTIPLY);
            }
            vv.invalidate();
            return;
        }

        // special cases

        if (type.equals("linear-layout")) {
            //Log.i("starwisp","linear-layout update id: "+id);
            StarwispLinearLayout.Update(this, (LinearLayout) vv, token, ctx, ctxname, arr);
            return;
        }

        if (type.equals("relative-layout")) {
            StarwispRelativeLayout.Update(this, (RelativeLayout) vv, token, ctx, ctxname, arr);
            return;
        }

        if (type.equals("draggable")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }

            if (token.equals("contents-add")) {
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;

            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing on click data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing pages data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                v.setImageBitmap(BitmapCache.Load(arr.getString(3)));
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(Html.fromHtml(arr.getString(3)), BufferType.SPANNABLE);
                //                    v.invalidate();
            }
            if (token.equals("file")) {
                v.setText(LoadData(arr.getString(3)));
            }

            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] input, Camera camera) {
                        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
                        Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);

                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, blob.toByteArray());
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            // don't shut the activity down and use provided path
            if (token.equals("take-picture-cont")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                Log.i("starwisp", "take-picture-cont fired");

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] input, Camera camera) {
                        Log.i("starwisp", "on picture taken...");

                        // the version used by the uav app

                        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
                        //Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        original.compress(Bitmap.CompressFormat.JPEG, 95, blob);
                        original.recycle();
                        String filename = path;
                        Log.i("starwisp", path);
                        SaveData(filename, blob.toByteArray());

                        // burn gps into exif data
                        if (m_GPS.currentLocation != null) {
                            double latitude = m_GPS.currentLocation.getLatitude();
                            double longitude = m_GPS.currentLocation.getLongitude();

                            try {
                                ExifInterface exif = new ExifInterface(filename);
                                exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, GPS.convert(latitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                                        GPS.latitudeRef(latitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, GPS.convert(longitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                                        GPS.longitudeRef(longitude));
                                exif.saveAttributes();
                            } catch (IOException e) {
                                Log.i("starwisp",
                                        "Couldn't open " + filename + " to add exif data: ioexception caught.");
                            }

                        }

                        v.TakenPicture();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                        spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);
                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        CallbackArgs(ctx, ctxname, wid, "" + pos);
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

        if (type.equals("draw-map")) {
            DrawableMap v = m_DMaps.get(id);
            if (v != null) {
                if (token.equals("polygons")) {
                    v.UpdateFromJSON(arr.getJSONArray(3));
                }
                if (token.equals("centre")) {
                    JSONArray tokens = arr.getJSONArray(3);
                    v.Centre(tokens.getDouble(0), tokens.getDouble(1), tokens.getInt(2));
                }
                if (token.equals("layout")) {
                    v.m_parent.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
                }
            } else {
                Log.e("starwisp", "Asked to update a drawmap which doesn't exist");
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing builder data " + e.toString());
        Log.e("starwisp", "type:" + type + " id:" + id + " token:" + token);
    }
}

From source file:com.android.mail.utils.NotificationUtils.java

public static ContactIconInfo getContactInfo(final Context context, final String senderAddress,
        final int idealIconWidth, final int idealIconHeight, final int idealWearableBgWidth,
        final int idealWearableBgHeight) {
    final ContactIconInfo contactIconInfo = new ContactIconInfo();
    final List<Long> contactIds = findContacts(context, Arrays.asList(new String[] { senderAddress }));

    if (contactIds != null) {
        for (final long id : contactIds) {
            final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
            final InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
                    context.getContentResolver(), contactUri, true /*preferHighres*/);

            if (inputStream != null) {
                try {
                    final Bitmap source = BitmapFactory.decodeStream(inputStream);
                    if (source != null) {
                        // We should scale this image to fit the intended size
                        contactIconInfo.icon = Bitmap.createScaledBitmap(source, idealIconWidth,
                                idealIconHeight, true);

                        contactIconInfo.wearableBg = Bitmap.createScaledBitmap(source, idealWearableBgWidth,
                                idealWearableBgHeight, true);
                    }//from   ww w  .  ja  va 2s .  c o m

                    if (contactIconInfo.icon != null) {
                        break;
                    }
                } finally {
                    Closeables.closeQuietly(inputStream);
                }
            }
        }
    }

    return contactIconInfo;
}

From source file:com.android.mms.ui.MessageUtils.java

/** M: Code analyze 021, For fix bug ALPS00279524, The "JE" about "MMS"
 * pops up after we launch "Messaging" again.
 *
 * @param bitmap//  w ww  . j  a va  2s. co m
 * @param maxWidth
 * @param maxHeight
 * @return
 */
public static Bitmap getResizedBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
    if (bitmap == null) {
        return bitmap;
    }
    int originWidth = bitmap.getWidth();
    int originHeight = bitmap.getHeight();

    if (originWidth < maxWidth && originHeight < maxHeight) {
        return bitmap;
    }

    int width = originWidth;
    int height = originHeight;

    if (originWidth > maxWidth) {
        width = maxWidth;
        double i = originWidth * 1.0 / maxWidth;
        height = (int) Math.floor(originHeight / i);
        Bitmap mBitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
        return mBitmap;
    }

    if (originHeight > maxHeight) {
        height = maxHeight;
        double i = originHeight * 1.0 / maxHeight;
        width = (int) Math.floor(originWidth / i);
        Bitmap mBitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
        return mBitmap;
    }

    return bitmap;
}