Example usage for android.view Display getWidth

List of usage examples for android.view Display getWidth

Introduction

In this page you can find the example usage for android.view Display getWidth.

Prototype

@Deprecated
public int getWidth() 

Source Link

Usage

From source file:com.cloverstudio.spika.CameraCropActivity.java

public void scaleView() {
    // instantiate the views
    View top_view = findViewById(R.id.topView);
    View bottom_view = findViewById(R.id.bottomView);
    LinearLayout footer = (LinearLayout) findViewById(R.id.llFooter);
    LinearLayout crop_frame = (LinearLayout) findViewById(R.id.llCropFrame);
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();

    // 90% of width
    crop_container_size = (int) ((float) width * (1f - (10f / 100f)));

    // 10% margins
    float margin = ((float) width * (1f - (90f / 100f)));

    // Parameters for white crop border
    LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(crop_container_size, crop_container_size);
    par.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
    par.setMargins((int) (margin / 2f), 0, (int) (margin / 2f), 0);
    crop_frame.setLayoutParams(par);/*from w  ww  .j a v a  2s.c o  m*/

    // Margins for other transparent views
    float top_view_height = ((float) (height - crop_container_size - footer.getHeight())) / (float) 2;
    top_view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) top_view_height));
    bottom_view
            .setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) top_view_height));

    // Image container
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(crop_container_size,
            crop_container_size);
    params.setMargins((int) (margin / 2f), (int) top_view_height, (int) (margin / 2f), 0);
    mImageView.setLayoutParams(params);
    mImageView.setImageBitmap(mBitmap);
    mImageView.setMaxZoom(4f);
}

From source file:com.nextgis.mobile.fragment.LayersFragment.java

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId//from  w w w  . j  a va2  s  . co m
 *         The android:id of this fragment in its activity's layout.
 * @param drawerLayout
 *         The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout, final MapDrawable map) {
    MainActivity activity = (MainActivity) getActivity();
    mFragmentContainerView = activity.findViewById(fragmentId);

    Display display = activity.getWindowManager().getDefaultDisplay();

    int displayWidth;
    if (android.os.Build.VERSION.SDK_INT >= 13) {
        Point size = new Point();
        display.getSize(size);
        displayWidth = size.x;
    } else {
        displayWidth = display.getWidth();
    }

    ViewGroup.LayoutParams params = mFragmentContainerView.getLayoutParams();
    if (params.width >= displayWidth) {
        params.width = (int) (displayWidth * 0.8);
    }
    mFragmentContainerView.setLayoutParams(params);

    final MapFragment mapFragment = activity.getMapFragment();
    mListAdapter = new LayersListAdapter(activity, mapFragment.mMap);
    mListAdapter.setDrawer(drawerLayout);
    mListAdapter.setOnPencilClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mapFragment.hasEdits()) {
                if (mapFragment.mFinishListener != null)
                    mapFragment.mFinishListener.onClick(null);
                return;
            }

            AlertDialog builder = new AlertDialog.Builder(getContext()).setTitle(R.string.save)
                    .setMessage(R.string.has_edits)
                    .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mapFragment.saveEdits();
                            mapFragment.setMode(MapFragment.MODE_NORMAL);
                        }
                    }).setNegativeButton(R.string.discard, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mapFragment.cancelEdits();
                            mapFragment.setMode(MapFragment.MODE_NORMAL);
                        }
                    }).create();
            builder.show();
        }
    });
    mListAdapter.setOnLayerEditListener(new LayersListAdapter.onEdit() {
        @Override
        public void onLayerEdit(ILayer layer) {
            IGISApplication application = (IGISApplication) getActivity().getApplication();
            application.sendEvent(GA_LAYER, GA_EDIT, GA_MENU);
            mapFragment.onFinishChooseLayerDialog(MapFragment.EDIT_LAYER, layer);
            toggle();
        }
    });
    mapFragment.setOnModeChangeListener(new MapFragment.onModeChange() {
        @Override
        public void onModeChangeListener() {
            mListAdapter.notifyDataSetChanged();
        }
    });

    mLayersListView = (ReorderedLayerView) mFragmentContainerView.findViewById(R.id.layer_list);
    mLayersListView.setAdapter(mListAdapter);
    mLayersListView.setDrawer(drawerLayout);

    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.

    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), // host Activity
            mDrawerLayout, // DrawerLayout object
            //                R.drawable.ic_drawer,             // nav drawer image to replace 'Up' caret
            R.string.layers_drawer_open,
            // "open drawer" description for accessibility
            R.string.layers_drawer_close
    // "close drawer" description for accessibility
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }

            setupSyncOptions();
            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // Defer code dependent on restoration of previous instance state.
    syncState();
}

From source file:com.gmail.walles.johan.batterylogger.BatteryPlotFragment.java

private void initializeLegend(final TextView legend) {
    // From: http://stackoverflow.com/questions/6068197/utils-read-resource-text-file-to-string-java#answer-18897411
    String html = new Scanner(this.getClass().getResourceAsStream("/legend.html"), "UTF-8").useDelimiter("\\A")
            .next();/*from   w  w  w . j a v a 2 s.co  m*/
    legend.setText(trimTrailingWhitespace(Html.fromHtml(html)));

    // Check MainActivity.PREF_SHOW_LEGEND and set legend visibility from that
    SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
    boolean showLegend = preferences.getBoolean(MainActivity.PREF_SHOW_LEGEND, true);
    legend.setVisibility(showLegend ? View.VISIBLE : View.GONE);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        int width = (int) spToPixels(LEGEND_WIDTH_LANDSCAPE_SP);

        // Put an upper bound on the legend width at 40% landscape screen width
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        //noinspection deprecation
        int landscapeWidth = Math.max(display.getWidth(), display.getHeight());
        if (width > landscapeWidth * 0.4) {
            width = (int) (landscapeWidth * 0.4);
        }

        legend.getLayoutParams().width = width;
    }
}

From source file:com.hp.map.CustomerMapActivity.java

public void menuDialog() {
    final Dialog dialog = new Dialog(this);
    LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = li.inflate(R.layout.menu_dialog, null, false);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(v);/*from  w  w  w . j a  v a 2  s  .c  o  m*/

    dialog.setTitle("Danh mc chnh");

    Display display = getWindowManager().getDefaultDisplay();

    dialog.getWindow().setLayout(2 * display.getWidth() / 3, LayoutParams.FILL_PARENT);
    dialog.getWindow().getAttributes().gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;

    lv = (ListView) dialog.findViewById(R.id.menu_list_view);

    lv.setAdapter(
            new DialogArrayAdapter(context, android.R.layout.simple_list_item_1, DetailListData.MENU_LIST));
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
            DetailsList selectedValue = (DetailsList) lv.getAdapter().getItem(arg2);
            if (selectedValue.activityClass != null) {
                //if sigout
                if (selectedValue.activityClass == LoginActivity.class) {
                    //LoginActivity.threadLooper.quit();
                }
                startActivity(new Intent(context, selectedValue.activityClass));
            }
        }
    });

    dialog.show();

    //      ImageView iv = (ImageView)dialog.findViewById(R.id.menu_list_view);
    //      iv.setImageResource(1);
}

From source file:im.neon.adapters.VectorMediasViewerAdapter.java

@SuppressLint("NewApi")
private Point getDisplaySize() {
    Point size = new Point();
    WindowManager w = ((Activity) mContext).getWindowManager();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        w.getDefaultDisplay().getSize(size);
    } else {// w w  w.  j av  a2s. c o m
        Display d = w.getDefaultDisplay();
        size.x = d.getWidth();
        size.y = d.getHeight();
    }

    return size;
}

From source file:com.microsoft.live.sample.skydrive.SkyDriveActivity.java

/**
 * Extract a photo from SkyDrive and creates a scaled bitmap according to the device resolution, this is needed to
 * prevent memory over-allocation that can cause some devices to crash when opening high-resolution pictures
 *
 * Note: this method should not be used for downloading photos, only for displaying photos on-screen
 *
 * @param photo The source photo to download
 * @param imageStream The stream that contains the photo
 * @return Scaled bitmap representation of the photo
 * @see http://stackoverflow.com/questions/477572/strange-out-of-memory-issue-while-loading-an-image-to-a-bitmap-object/823966#823966
 *///from   w  ww.j  a  va 2 s. c  o m
private Bitmap extractScaledBitmap(SkyDrivePhoto photo, InputStream imageStream) {
    Display display = getWindowManager().getDefaultDisplay();
    int IMAGE_MAX_SIZE = Math.max(display.getWidth(), display.getHeight());

    int scale = 1;
    if (photo.getHeight() > IMAGE_MAX_SIZE || photo.getWidth() > IMAGE_MAX_SIZE) {
        scale = (int) Math.pow(2,
                (int) Math
                        .ceil(Math.log(IMAGE_MAX_SIZE / (double) Math.max(photo.getHeight(), photo.getWidth()))
                                / Math.log(0.5)));
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPurgeable = true;
    options.inSampleSize = scale;
    return BitmapFactory.decodeStream(imageStream, (Rect) null, options);
}

From source file:com.mirasense.scanditsdk.plugin.ScanditSDK.java

/**
 * Adjusts the layout parameters of the barcode picker according to the margins set through java script.
 *
 * @param bundle The bundle with the java script parameters.
 * @param animationDuration Over how long the change should be animated.
 *//*from ww w. j  a  v  a2s  .  c  o m*/
private void adjustLayout(Bundle bundle, double animationDuration) {
    if (mBarcodePicker == null) {
        return;
    }
    final RelativeLayout.LayoutParams rLayoutParams = (RelativeLayout.LayoutParams) mBarcodePicker
            .getLayoutParams();

    Display display = ((WindowManager) webView.getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay();
    if (bundle.containsKey(ScanditSDKParameterParser.paramPortraitMargins)
            && display.getHeight() > display.getWidth()) {
        String portraitMargins = bundle.getString(ScanditSDKParameterParser.paramPortraitMargins);
        String[] split = portraitMargins.split("[/]");
        if (split.length == 4) {
            try {
                final Rect oldPortraitMargins = new Rect(mPortraitMargins);
                mPortraitMargins = new Rect(Integer.valueOf(split[0]), Integer.valueOf(split[1]),
                        Integer.valueOf(split[2]), Integer.valueOf(split[3]));
                if (animationDuration > 0) {
                    Animation anim = new Animation() {
                        @Override
                        protected void applyTransformation(float interpolatedTime, Transformation t) {
                            rLayoutParams.topMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                                    (int) (oldPortraitMargins.top
                                            + (mPortraitMargins.top - oldPortraitMargins.top)
                                                    * interpolatedTime));
                            rLayoutParams.rightMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                                    (int) (oldPortraitMargins.right
                                            + (mPortraitMargins.right - oldPortraitMargins.right)
                                                    * interpolatedTime));
                            rLayoutParams.bottomMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                                    (int) (oldPortraitMargins.bottom
                                            + (mPortraitMargins.bottom - oldPortraitMargins.bottom)
                                                    * interpolatedTime));
                            rLayoutParams.leftMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                                    (int) (oldPortraitMargins.left
                                            + (mPortraitMargins.left - oldPortraitMargins.left)
                                                    * interpolatedTime));
                            mBarcodePicker.setLayoutParams(rLayoutParams);
                        }
                    };
                    anim.setDuration((int) (animationDuration * 1000));
                    mBarcodePicker.startAnimation(anim);
                } else {

                    rLayoutParams.topMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            mPortraitMargins.top);
                    rLayoutParams.rightMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            mPortraitMargins.right);
                    rLayoutParams.bottomMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            mPortraitMargins.bottom);
                    rLayoutParams.leftMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            mPortraitMargins.left);
                    mBarcodePicker.setLayoutParams(rLayoutParams);
                }
            } catch (NumberFormatException e) {

            }
        }
    } else if (bundle.containsKey(ScanditSDKParameterParser.paramLandscapeMargins)
            && display.getWidth() > display.getHeight()) {
        String landscapeMargins = bundle.getString(ScanditSDKParameterParser.paramLandscapeMargins);
        String[] split = landscapeMargins.split("[/]");
        if (split.length == 4) {
            final Rect oldLandscapeMargins = new Rect(mLandscapeMargins);
            mLandscapeMargins = new Rect(Integer.valueOf(split[0]), Integer.valueOf(split[1]),
                    Integer.valueOf(split[2]), Integer.valueOf(split[3]));

            Animation anim = new Animation() {
                @Override
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    rLayoutParams.topMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            (int) (oldLandscapeMargins.top
                                    + (mLandscapeMargins.top - oldLandscapeMargins.top) * interpolatedTime));
                    rLayoutParams.rightMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            (int) (oldLandscapeMargins.right
                                    + (mLandscapeMargins.right - oldLandscapeMargins.right)
                                            * interpolatedTime));
                    rLayoutParams.bottomMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            (int) (oldLandscapeMargins.bottom
                                    + (mLandscapeMargins.bottom - oldLandscapeMargins.bottom)
                                            * interpolatedTime));
                    rLayoutParams.leftMargin = SbSystemUtils.pxFromDp(webView.getContext(),
                            (int) (oldLandscapeMargins.left
                                    + (mLandscapeMargins.left - oldLandscapeMargins.left) * interpolatedTime));
                    mBarcodePicker.setLayoutParams(rLayoutParams);
                }
            };
            anim.setDuration((int) (animationDuration * 1000));
            mBarcodePicker.startAnimation(anim);
        }
    }
}

From source file:de.madvertise.android.sdk.MadView.java

/**
 * Starts a background thread to fetch a new ad. Method is called
 * from the refresh timer task//w  w  w .  j av  a  2 s .c  om
 */
private void requestNewAd() {
    MadUtil.logMessage(null, Log.DEBUG, "Trying to fetch a new ad");

    // exit if already requesting a new ad, not used yet
    if (runningRefreshAd) {
        MadUtil.logMessage(null, Log.DEBUG, "Another request is still in progress ...");
        return;
    }

    new Thread() {
        public void run() {
            // read all parameters, that we need for the request
            // get site token from manifest xml file
            String siteToken = MadUtil.getToken(getContext());
            if (siteToken == null) {
                siteToken = "";
                MadUtil.logMessage(null, Log.DEBUG, "Cannot show ads, since the appID ist null");
            } else {
                MadUtil.logMessage(null, Log.DEBUG, "appID = " + siteToken);
            }

            // get uid (does not work in emulator)
            String uid = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
            if (uid == null) {
                uid = "";
            } else {
                uid = getMD5Hash(uid);
            }
            MadUtil.logMessage(null, Log.DEBUG, "uid = " + uid);

            // get display metrics
            Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay();
            int displayHeight = display.getHeight();
            int displayWidth = display.getWidth();
            MadUtil.logMessage(null, Log.DEBUG, "Display height = " + Integer.toString(displayHeight));
            MadUtil.logMessage(null, Log.DEBUG, "Display width = " + Integer.toString(displayWidth));

            // create post request
            HttpPost postRequest = new HttpPost(MadUtil.MAD_SERVER + "/site/" + siteToken);
            postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

            List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
            parameterList.add(new BasicNameValuePair("ua", MadUtil.getUA()));
            parameterList.add(new BasicNameValuePair("app", "true"));
            parameterList.add(new BasicNameValuePair("debug", Boolean.toString(testMode)));
            parameterList.add(new BasicNameValuePair("ip", MadUtil.getLocalIpAddress()));
            parameterList.add(new BasicNameValuePair("format", "json"));
            parameterList.add(new BasicNameValuePair("requester", "android_sdk"));
            parameterList.add(new BasicNameValuePair("version", "1.1"));
            parameterList.add(new BasicNameValuePair("uid", uid));
            parameterList.add(new BasicNameValuePair("banner_type", bannerType));
            parameterList.add(new BasicNameValuePair("deliver_only_text", Boolean.toString(deliverOnlyText)));

            MadUtil.refreshCoordinates(getContext());
            if (MadUtil.getLocation() != null) {
                parameterList.add(
                        new BasicNameValuePair("lat", Double.toString(MadUtil.getLocation().getLatitude())));
                parameterList.add(
                        new BasicNameValuePair("lng", Double.toString(MadUtil.getLocation().getLongitude())));
            }

            UrlEncodedFormEntity urlEncodedEntity = null;
            try {
                urlEncodedEntity = new UrlEncodedFormEntity(parameterList);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            postRequest.setEntity(urlEncodedEntity);

            MadUtil.logMessage(null, Log.DEBUG, "Post request created");
            MadUtil.logMessage(null, Log.DEBUG, "Uri : " + postRequest.getURI().toASCIIString());
            MadUtil.logMessage(null, Log.DEBUG,
                    "All headers : " + MadUtil.getAllHeadersAsString(postRequest.getAllHeaders()));
            MadUtil.logMessage(null, Log.DEBUG,
                    "All request parameters :" + MadUtil.printRequestParameters(parameterList));

            synchronized (this) {
                // send blocking request to ad server
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = null;
                InputStream inputStream = null;
                boolean jsonFetched = false;
                JSONObject json = null;

                try {
                    HttpParams clientParams = httpClient.getParams();
                    HttpConnectionParams.setConnectionTimeout(clientParams,
                            MadUtil.CONNECTION_TIMEOUT.intValue());
                    HttpConnectionParams.setSoTimeout(clientParams, MadUtil.CONNECTION_TIMEOUT.intValue());

                    MadUtil.logMessage(null, Log.DEBUG, "Sending request");
                    httpResponse = httpClient.execute(postRequest);

                    MadUtil.logMessage(null, Log.DEBUG,
                            "Response Code => " + httpResponse.getStatusLine().getStatusCode());
                    if (testMode)
                        MadUtil.logMessage(null, Log.DEBUG, "Madvertise Debug Response: "
                                + httpResponse.getLastHeader("X-Madvertise-Debug"));
                    int responseCode = httpResponse.getStatusLine().getStatusCode();

                    HttpEntity entity = httpResponse.getEntity();

                    if (responseCode == 200 && entity != null) {
                        inputStream = entity.getContent();
                        String resultString = MadUtil.convertStreamToString(inputStream);
                        MadUtil.logMessage(null, Log.DEBUG, "Response => " + resultString);
                        json = new JSONObject(resultString);
                        jsonFetched = true;
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                    MadUtil.logMessage(null, Log.DEBUG, "Error in HTTP request / protocol");
                } catch (IOException e) {
                    e.printStackTrace();
                    MadUtil.logMessage(null, Log.DEBUG, "Could not receive a http response on an ad reqeust");
                } catch (JSONException e) {
                    e.printStackTrace();
                    MadUtil.logMessage(null, Log.DEBUG, "Could not parse json object");
                } finally {
                    if (inputStream != null)
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                        }
                }

                // create ad, this is a blocking call
                if (jsonFetched) {
                    currentAd = new Ad(getContext(), json);
                }
            }
            mHandler.post(mUpdateResults);

        }
    }.start();
}

From source file:org.openqa.selendroid.server.model.DefaultSelendroidDriver.java

@Override
@SuppressWarnings("deprecation")
public byte[] takeScreenshot() {
    ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance();

    // TODO ddary review later, but with getRecentDecorView() it seems to work better
    // long drawingTime = 0;
    // View container = null;
    // for (View view : viewAnalyzer.getTopLevelViews()) {
    // if (view != null && view.isShown() && view.hasWindowFocus()
    // && view.getDrawingTime() > drawingTime) {
    // container = view;
    // drawingTime = view.getDrawingTime();
    // }/*from   www .  j  a  v a2  s .  c  om*/
    // }
    // final View mainView = container;
    final View mainView = viewAnalyzer.getRecentDecorView();
    if (mainView == null) {
        throw new SelendroidException("No open windows.");
    }
    done = false;
    long end = System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis();
    final byte[][] rawPng = new byte[1][1];
    ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() {
        public void run() {
            synchronized (syncObject) {
                Display display = serverInstrumentation.getCurrentActivity().getWindowManager()
                        .getDefaultDisplay();
                Point size = new Point();
                try {
                    display.getSize(size);
                } catch (NoSuchMethodError ignore) { // Older than api level 13
                    size.x = display.getWidth();
                    size.y = display.getHeight();
                }

                // Get root view
                View view = mainView.getRootView();

                // Create the bitmap to use to draw the screenshot
                final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888);
                final Canvas canvas = new Canvas(bitmap);

                // Get current theme to know which background to use
                final Activity activity = serverInstrumentation.getCurrentActivity();
                final Theme theme = activity.getTheme();
                final TypedArray ta = theme
                        .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
                final int res = ta.getResourceId(0, 0);
                final Drawable background = activity.getResources().getDrawable(res);

                // Draw background
                background.draw(canvas);

                // Draw views
                view.draw(canvas);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)) {
                    throw new RuntimeException("Error while compressing screenshot image.");
                }
                try {
                    stream.flush();
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
                } finally {
                    Closeable closeable = (Closeable) stream;
                    try {
                        if (closeable != null) {
                            closeable.close();
                        }
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
                rawPng[0] = stream.toByteArray();
                mainView.destroyDrawingCache();
                done = true;
                syncObject.notify();
            }
        }
    });

    waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(), "Failed to take screenshot.");
    return rawPng[0];
}

From source file:com.undatech.opaque.RemoteCanvas.java

public RemoteCanvas(final Context context, AttributeSet attrSet) {
    super(context, attrSet);
    clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
    final Display display = ((Activity) context).getWindow().getWindowManager().getDefaultDisplay();
    displayWidth = display.getWidth();
    displayHeight = display.getHeight();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);/* w  w  w .  j  a  v  a  2s . com*/
    displayDensity = metrics.density;

    canvasZoomer = new CanvasZoomer(this);
    setScaleType(ImageView.ScaleType.MATRIX);

    if (android.os.Build.MODEL.contains("BlackBerry") || android.os.Build.BRAND.contains("BlackBerry")
            || android.os.Build.MANUFACTURER.contains("BlackBerry")) {
        bb = true;
    }
}