Example usage for android.util DisplayMetrics DisplayMetrics

List of usage examples for android.util DisplayMetrics DisplayMetrics

Introduction

In this page you can find the example usage for android.util DisplayMetrics DisplayMetrics.

Prototype

public DisplayMetrics() 

Source Link

Usage

From source file:system.info.reader.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    resolutions = Properties.resolution(dm);
    Properties.resolution = resolutions[0] + "*" + resolutions[1];
    int tabHeight = 30, tabWidth = 80;
    if (dm.widthPixels >= 480) {
        tabHeight = 40;/*from  w  w  w  .ja  va  2 s. c o  m*/
        tabWidth = 120;
    }

    tabHost = getTabHost();
    LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);
    tabHost.addTab(
            tabHost.newTabSpec("tab1").setIndicator(getString(R.string.brief)).setContent(R.id.PropertyList));
    tabHost.addTab(
            tabHost.newTabSpec("tab2").setIndicator(getString(R.string.online)).setContent(R.id.ViewServer));
    tabHost.addTab(
            tabHost.newTabSpec("tab3").setIndicator(getString(R.string.apps)).setContent(R.id.sViewApps));
    tabHost.addTab(
            tabHost.newTabSpec("tab4").setIndicator(getString(R.string.process)).setContent(R.id.sViewProcess));
    tabHost.addTab(tabHost.newTabSpec("tab5").setIndicator("Services").setContent(R.id.sViewCpu));
    tabHost.addTab(tabHost.newTabSpec("tab6").setIndicator("Tasks").setContent(R.id.sViewMem));
    //tabHost.addTab(tabHost.newTabSpec("tab7")
    //        .setIndicator("Vending")
    //        .setContent(R.id.sViewDisk));
    AppsText = (TextView) findViewById(R.id.TextViewApps);
    ProcessText = (TextView) findViewById(R.id.TextViewProcess);
    ServiceText = (TextView) findViewById(R.id.TextViewCpu);
    TaskText = (TextView) findViewById(R.id.TextViewMem);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(tabWidth, tabHeight);
    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++)
        tabHost.getTabWidget().getChildAt(i).setLayoutParams(lp);

    properList = (ListView) findViewById(R.id.PropertyList);
    Properties.properListItem = new ArrayList<HashMap<String, Object>>();
    properListItemAdapter = new SimpleAdapter(this, Properties.properListItem, R.layout.property_list,
            new String[] { "ItemTitle", "ItemText" }, new int[] { R.id.ItemTitle, R.id.ItemText });
    properList.setAdapter(properListItemAdapter);
    properList.setOnItemClickListener(mpropertyCL);

    //will support app list later
    //appList = (ListView)findViewById(R.id.AppList);
    //Properties.appListItem = new ArrayList<HashMap<String, Object>>();  
    //SimpleAdapter appListItemAdapter = new SimpleAdapter(this, Properties.appListItem,   
    //             R.layout.app_list,  
    //             new String[] {"ItemTitle", "ItemText"},   
    //             new int[] {R.id.ItemTitle, R.id.ItemText}  
    //         );  
    //appList.setAdapter(appListItemAdapter);

    serverWeb = (WebView) findViewById(R.id.ViewServer);
    WebSettings webSettings = serverWeb.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString("sys.info.trial" + versionCode);
    webSettings.setTextSize(WebSettings.TextSize.SMALLER);
    serverWeb.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;//this will not launch browser when redirect.
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    });

    PackageManager pm = getPackageManager();
    try {
        PackageInfo pi = pm.getPackageInfo("sys.info.trial", 0);
        version = "v" + pi.versionName;
        versionCode = pi.versionCode;

        List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
        nApk = Integer.toString(apps.size());
        apklist = "";
        for (PackageInfo app : apps) {
            apklist += app.packageName + "\t(" + app.versionName + ")\n";
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    showDialog(0);
    initPropList();
    //refresh();
    PageTask task = new PageTask();
    task.execute("");
}

From source file:com.wheelphone.remotemini.WheelphoneRemoteMini.java

private void storeScreenDimensions() {
    // Query display dimensions:
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    mScreenWidth = metrics.widthPixels;// w  w  w .  j  av a 2s. co m
    mScreenHeight = metrics.heightPixels;
}

From source file:com.malgon.applecrunch.Game3.java

public void onCreate() {
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    screenHeight = dm.heightPixels;// w  ww . j  a v  a 2  s . c o m
    screenWidth = dm.widthPixels;

    createEngine("graphics/splash2.png", screenWidth, screenHeight, false);

    alertDialog = new AlertDialog.Builder(Game3.this).create();
    alertDialog.setTitle("Game3 Finished");
    alertDialog.setButton("Play again", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            score = 0;
            appleTouch = 0;
            androidTouch = 0;
            time = timeToPlay / 1000;
            textScore.setText(String.valueOf(score));
            rokon.unfreeze();

            timer.postDelayed(endOfGame1, timeToPlay);
        }
    });
    alertDialog.setButton2("Quit", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            System.exit(0);
            Game3.this.finish();
        }
    });

    scoreDialog = new AlertDialog.Builder(Game3.this).create();
    scoreDialog.setTitle("Send score ?");
    scoreDialog.setButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(Game3.this);

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url + "?key=o2BY3XUF0AgytDdaLmugnXiFUfRRQF&username="
                    + pref.getString("username", "Player Default").replace(" ", "+") + "&score=" + score
                    + "&type=2");
            try {
                httpclient.execute(get);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String msg = "Game finished, you've killed apple " + appleTouch + " time ! ";

            if (androidTouch > 0) {
                msg += "But you killed Android " + androidTouch + " time :( ";
                msg += "Next time don't kill Android, because it will eat apples :D ";
            } else if (appleTouch == 0) {
                msg += "Don't be afraid of apple ;) ";
            } else
                msg += "You are now an Android lover, and an apple killer :D ";

            msg += "Your final score is " + score;

            alertDialog.setMessage(msg);

            alertDialog.show();
        }
    });
    scoreDialog.setButton2("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            String msg = "Game finished, you've killed apple " + appleTouch + " time ! ";

            if (androidTouch > 0) {
                msg += "But you killed Android " + androidTouch + " time :( ";
                msg += "Next time don't kill Android, because it will eat apples :D ";
            } else if (appleTouch == 0) {
                msg += "Don't be afraid of apple ;) ";
            } else
                msg += "You are now an Android lover, and an apple killer :D ";

            msg += "Your final score is " + score;

            alertDialog.setMessage(msg);

            alertDialog.show();
        }
    });

    goalDialog = new AlertDialog.Builder(Game3.this).create();
    goalDialog.setTitle("Goal");
    goalDialog.setMessage(
            "The goal of this game, is to shoot apple sprites, by clicking on touchpad center. You can move your phone sprite, using screen or touchpad. Care to don't kill Android sprites ! To get more points, catch Android Sprites with the phone sprite.");
    goalDialog.setButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            timer.postDelayed(endOfGame1, timeToPlay);
            timerTime.postDelayed(checkTime, 1000);
            timerAndroid.postDelayed(checkAndroid, 1000);
        }
    });
}

From source file:com.mappn.gfan.ui.HomeTabActivity.java

private void drawUpdateCount(Activity context, Resources res, ImageView view, boolean flag) {
    DisplayMetrics dm = new DisplayMetrics();
    context.getWindowManager().getDefaultDisplay().getMetrics(dm);
    Bitmap cornerRes = BitmapFactory.decodeResource(res, R.drawable.notify_update);
    Bitmap appBitmapNormal = BitmapFactory.decodeResource(res, R.drawable.main_tab_app_unselect);
    Bitmap appBitmapPressed = BitmapFactory.decodeResource(res, R.drawable.main_tab_app_select);

    StateListDrawable stateDrawable = new StateListDrawable();
    int stateSelected = android.R.attr.state_selected;
    if (flag) {//  w ww .j  a  v  a  2s  .c  o  m
        Bitmap cornerBitmap = drawText(dm, res, cornerRes, mSession.getUpgradeNumber());
        Bitmap newBitmapNormal = drawBitmap(dm, appBitmapNormal, cornerBitmap);
        Bitmap newBitmapPressed = drawBitmap(dm, appBitmapPressed, cornerBitmap);

        stateDrawable.addState(new int[] { -stateSelected }, new BitmapDrawable(res, newBitmapNormal));
        stateDrawable.addState(new int[] { stateSelected }, new BitmapDrawable(res, newBitmapPressed));

        view.setImageDrawable(stateDrawable);
    } else {

        view.setImageResource(R.drawable.main_tab_app_manager_selector);
    }
}

From source file:com.twitterdev.rdio.app.RdioApp.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();//from w w w.j  a v  a 2s. com
        player.release();
        player = null;
    }

    final Track track = trackQueue.poll();
    if (trackQueue.size() < 3) {
        Log.i(TAG, "Track queue depleted, loading more tracks");
        LoadMoreTracks();
    }

    if (track == null) {
        Log.e(TAG, "Track is null!  Size of queue: " + trackQueue.size());
        return;
    }

    // Load the next track in the background and prep the player (to start buffering)
    // Do this in a bkg thread so it doesn't block the main thread in .prepare()
    AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() {
        @Override
        protected Track doInBackground(Track... params) {
            Track track = params[0];
            final String trackName = track.artistName;
            final String artist = track.trackName;
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
                new getSearch().execute(track.trackName);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView a = (TextView) findViewById(R.id.artist);
                        //a.setText(artist);
                        TextView t = (TextView) findViewById(R.id.track);
                        //t.setText(trackName);
                    }
                });

            } catch (Exception e) {
                Log.e("Test", "Exception " + e);
            }
            return track;
        }

        @Override
        protected void onPostExecute(Track track) {
            updatePlayPause(true);
        }
    };
    task.execute(track);

    // Fetch album art in the background and then update the UI on the main thread
    AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Track... params) {
            Track track = params[0];
            try {
                String artworkUrl = track.albumArt.replace("square-200", "square-600");
                Log.i(TAG, "Downloading album art: " + artworkUrl);
                Bitmap bm = null;
                try {
                    URL aURL = new URL(artworkUrl);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error getting bitmap", e);
                }
                return bm;
            } catch (Exception e) {
                Log.e(TAG, "Error downloading artwork", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap artwork) {
            if (artwork != null) {
                int imageWidth = artwork.getWidth();
                int imageHeight = artwork.getHeight();
                DisplayMetrics dimension = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dimension);
                int newWidth = dimension.widthPixels;

                float scaleFactor = (float) newWidth / (float) imageWidth;
                int newHeight = (int) (imageHeight * scaleFactor);

                artwork = Bitmap.createScaledBitmap(artwork, newWidth, newHeight, true);
                //albumArt.setImageBitmap(bitmap);

                albumArt.setAdjustViewBounds(true);
                albumArt.setImageBitmap(artwork);

            } else
                albumArt.setImageResource(R.drawable.blank_album_art);
        }
    };
    artworkTask.execute(track);

    //Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName, track.albumName, track.artistName), Toast.LENGTH_LONG).show();
}

From source file:com.arisprung.tailgate.utilities.FacebookImageLoader.java

public static int calculateDensityDpi(Context context) {
    if (mDensityDpi > 0) {
        // we've already calculated it
        return mDensityDpi;
    }/*from w ww  .j  a v a2s  .c  o  m*/

    if (Integer.parseInt(Build.VERSION.SDK) <= 3) {
        // 1.5 devices are all medium density
        mDensityDpi = DENSITY_MEDIUM;
        return mDensityDpi;
    }

    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    int reflectedDensityDpi = DENSITY_MEDIUM;

    // try
    // {
    // reflectedDensityDpi = DisplayMetrics.class.getDeclaredField("mDensityDpi").getInt(metrics);
    // }
    // catch (Exception e)
    // {
    // e.printStackTrace();
    // }

    mDensityDpi = reflectedDensityDpi;
    return mDensityDpi;
}

From source file:tr.com.turkcellteknoloji.turkcellupdater.Utilities.java

@SuppressLint("NewApi")
static int getScreenOrientation(Activity activity) {
    if (Build.VERSION.SDK_INT < 8) {
        switch (activity.getResources().getConfiguration().orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        case Configuration.ORIENTATION_LANDSCAPE:
            return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        default:/*from  ww  w  .  j a  v  a2  s  .  c o  m*/
            return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        }
    }

    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    DisplayMetrics dm = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width = dm.widthPixels;
    int height = dm.heightPixels;
    int orientation;
    // if the device's natural orientation is portrait:
    if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width
            || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height) {
        switch (rotation) {
        case Surface.ROTATION_0:
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            break;
        case Surface.ROTATION_90:
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            break;
        case Surface.ROTATION_180:
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            break;
        case Surface.ROTATION_270:
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            break;
        default:
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            break;
        }
    }
    // if the device's natural orientation is landscape or if the device
    // is square:
    else {
        switch (rotation) {
        case Surface.ROTATION_0:
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            break;
        case Surface.ROTATION_90:
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            break;
        case Surface.ROTATION_180:
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            break;
        case Surface.ROTATION_270:
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            break;
        default:
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            break;
        }
    }

    return orientation;
}

From source file:it.angrydroids.epub3reader.TextSelectionSupport.java

private float getDensityDependentValue(float val, Context ctx) {
    Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);/*from   ww  w.  ja  va 2  s  . com*/
    return val * (metrics.densityDpi / 160f);
}

From source file:com.microsoft.windowsazure.mobileservices.authentication.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 *
 * @param startUrl The initial URL for the authentication process
 * @param endUrl   The final URL for the authentication process
 * @param context  The context used to create the authentication dialog
 * @param callback Callback to invoke when the authentication process finishes
 *///from www.jav a2 s.  c  o m
private void showLoginUIInternal(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels - 100;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished

            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:it.angrydroids.epub3reader.TextSelectionSupport.java

private float getDensityIndependentValue(float val, Context ctx) {
    Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);/*  w  w  w.  j a va 2s  .  c o m*/
    return val / (metrics.densityDpi / 160f);
}