Example usage for android.graphics Point Point

List of usage examples for android.graphics Point Point

Introduction

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

Prototype

public Point() 

Source Link

Usage

From source file:com.android.soma.Launcher.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (DEBUG_STRICT_MODE) {
        StrictMode.setThreadPolicy(/* w w  w .  ja va2  s  .  co  m*/
                new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems
                        .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
    }

    super.onCreate(savedInstanceState);

    LauncherAppState.setApplicationContext(getApplicationContext());
    LauncherAppState app = LauncherAppState.getInstance();

    // Determine the dynamic grid properties
    Point smallestSize = new Point();
    Point largestSize = new Point();
    Point realSize = new Point();
    Display display = getWindowManager().getDefaultDisplay();
    display.getCurrentSizeRange(smallestSize, largestSize);
    display.getRealSize(realSize);
    DisplayMetrics dm = new DisplayMetrics();
    display.getMetrics(dm);
    // Lazy-initialize the dynamic grid
    DeviceProfile grid = app.initDynamicGrid(this, Math.min(smallestSize.x, smallestSize.y),
            Math.min(largestSize.x, largestSize.y), realSize.x, realSize.y, dm.widthPixels, dm.heightPixels);

    // the LauncherApplication should call this, but in case of Instrumentation it might not be present yet
    mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
    mModel = app.setLauncher(this);
    mIconCache = app.getIconCache();
    mIconCache.flushInvalidIcons(grid);
    mDragController = new DragController(this);
    mInflater = getLayoutInflater();

    mStats = new Stats(this);

    mAppWidgetManager = AppWidgetManager.getInstance(this);

    mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
    mAppWidgetHost.startListening();

    // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
    // this also ensures that any synchronous binding below doesn't re-trigger another
    // LauncherModel load.
    mPaused = false;

    if (PROFILE_STARTUP) {
        android.os.Debug.startMethodTracing(Environment.getExternalStorageDirectory() + "/launcher");
    }

    checkForLocaleChange();
    setContentView(R.layout.launcher);

    setupViews();
    grid.layout(this);

    registerContentObservers();

    lockAllApps();

    mSavedState = savedInstanceState;
    restoreState(mSavedState);

    // Update customization drawer _after_ restoring the states
    if (mAppsCustomizeContent != null) {
        mAppsCustomizeContent.onPackagesUpdated(LauncherModel.getSortedWidgetsAndShortcuts(this));
    }
    {
        {
            final RajawaliSurfaceView surface = new RajawaliSurfaceView(this);
            surface.setFrameRate(60.0);
            surface.setRenderMode(IRajawaliSurface.RENDERMODE_WHEN_DIRTY);

            // Add mSurface to your root view
            addContentView(surface, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT));

            mRenderer = new WallpaperRenderer(this);
            surface.setSurfaceRenderer(mRenderer);
        }
    }

    if (PROFILE_STARTUP) {
        android.os.Debug.stopMethodTracing();
    }

    if (!mRestoring) {
        if (sPausedFromUserAction) {
            // If the user leaves launcher, then we should just load items asynchronously when
            // they return.
            mModel.startLoader(true, -1);
        } else {
            // We only load the page synchronously if the user rotates (or triggers a
            // configuration change) while launcher is in the foreground
            mModel.startLoader(true, mWorkspace.getCurrentPage());
        }
    }

    // For handling default keys
    mDefaultKeySsb = new SpannableStringBuilder();
    Selection.setSelection(mDefaultKeySsb, 0);

    IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    registerReceiver(mCloseSystemDialogsReceiver, filter);

    updateGlobalIcons();

    // On large interfaces, we want the screen to auto-rotate based on the current orientation
    unlockScreenOrientation(true);

    showFirstRunCling();

    //        following code is for Native method support test
    {

    }
}

From source file:com.example.javier.MaterialDesignApp.PlayerActivity.java

private float getCaptionFontSize() {
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    Point displaySize = new Point();
    display.getSize(displaySize);/*www  .j  av a 2s .c o  m*/
    return Math.max(getResources().getDimension(R.dimen.subtitle_minimum_font_size),
            CAPTION_LINE_HEIGHT_RATIO * Math.min(displaySize.x, displaySize.y));
}

From source file:com.eurotong.orderhelperandroid.OrderMenuActivity.java

@Override
public void afterTextChanged(Editable s) {
    try {// w  w  w.ja  va2s  .co  m
        Boolean flag = false;
        String key = editTextInput.getText().toString().trim().toLowerCase();
        if (key.contains("c")) {
            key = key.replace('c', 'c');
            flag = true;
        }
        if (key.contains("c")) {
            key = key.replace('c', 'c');
            flag = true;
        }
        if (key.contains("(")) {
            key = key.replace('(', 'c');
            flag = true;
        }
        if (key.contains("<")) {
            key = key.replace('<', 'c');
            flag = true;
        }

        int pos = key.indexOf("0");
        if (pos > 0) {
            if (key.charAt(pos - 1) >= '0' && key.charAt(pos - 1) <= '9') {
                key = key.replace('o', '0');
                flag = true;
            } else {
                key = key.replace('0', 'o');
                flag = true;
            }
        } else if (pos == 0) {
            key = key.replace('0', 'o');
            flag = true;
        }
        if (flag == true) {
            SetEditTextInputText(key);
        }

        Product[] menus = null;
        menus = ProductHints.Current().GetProductsByKeywords(key);
        menusContainer.removeAllViews();
        View filling = (View) getLayoutInflater().inflate(R.layout.order_menu_hint_fill_row, null);

        //http://stackoverflow.com/questions/1016896/android-how-to-get-screen-dimensions
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;

        filling.setMinimumHeight(height / 2);

        menusContainer.addView(filling);

        if (menus != null && menus.length > 0) {
            for (Product possiblemenu : menus) {
                for (VMMenuGroup menugroup : _lstVMMenuGroup) {
                    for (VMMenulistOrder menu : menugroup.VMMenus) {
                        if (possiblemenu.MenuNr.equals(menu.MenuNr)) {
                            View element = CreateMenuLine(menu);
                            menusContainer.addView(element);
                        }
                    }
                }
            }
        } else {
            //if(editTextInput.getText().toString().trim()!="")
            if (!editTextInput.getText().toString().trim().isEmpty()) {
                VMMenuGroup mg = new VMMenuGroup();
                mg.GroupName = getText(R.string.msg_no_mached_menu_found).toString();
                View element = CreateMenuGroupLine(mg);
                menusContainer.addView(element);
            }
        }
    } catch (Exception ex) {
        Log.e(Define.APP_CATALOG, ex.toString());
    }
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (DEBUG)/*w  w  w. j  av a 2  s.  co  m*/
        Log.d(TAG, "onCreate()");
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && !PermissionUtils.hasAccessAllEpg(this)) {
        Toast.makeText(this, R.string.msg_not_supported_device, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    boolean skipToShowOnboarding = getIntent().getAction() == Intent.ACTION_VIEW
            && TvContract.isChannelUriForPassthroughInput(getIntent().getData());
    if (Features.ONBOARDING_EXPERIENCE.isEnabled(this) && OnboardingUtils.needToShowOnboarding(this)
            && !skipToShowOnboarding && !TvCommonUtils.isRunningInTest()) {
        // TODO: The onboarding is turned off in test, because tests are broken by the
        // onboarding. We need to enable the feature for tests later.
        startActivity(OnboardingActivity.buildIntent(this, getIntent()));
        finish();
        return;
    }

    TvApplication tvApplication = (TvApplication) getApplication();
    tvApplication.getMainActivityWrapper().onMainActivityCreated(this);
    if (BuildConfig.ENG && SystemProperties.ALLOW_STRICT_MODE.getValue()) {
        Toast.makeText(this, "Using Strict Mode for eng builds", Toast.LENGTH_SHORT).show();
    }
    mTracker = tvApplication.getTracker();
    mTvInputManagerHelper = tvApplication.getTvInputManagerHelper();
    mTvInputManagerHelper.addCallback(mTvInputCallback);
    mUsbTunerInputId = UsbTunerTvInputService.getInputId(this);
    mChannelDataManager = tvApplication.getChannelDataManager();
    mProgramDataManager = tvApplication.getProgramDataManager();
    mProgramDataManager.addOnCurrentProgramUpdatedListener(Channel.INVALID_ID,
            mOnCurrentProgramUpdatedListener);
    mProgramDataManager.setPrefetchEnabled(true);
    mChannelTuner = new ChannelTuner(mChannelDataManager, mTvInputManagerHelper);
    mChannelTuner.addListener(mChannelTunerListener);
    mChannelTuner.start();
    mPipInputManager = new PipInputManager(this, mTvInputManagerHelper, mChannelTuner);
    mPipInputManager.start();
    mMemoryManageables.add(mProgramDataManager);
    mMemoryManageables.add(ImageCache.getInstance());
    mMemoryManageables.add(TvContentRatingCache.getInstance());
    if (CommonFeatures.DVR.isEnabled(this) && BuildCompat.isAtLeastN()) {
        mDvrManager = tvApplication.getDvrManager();
        mDvrDataManager = tvApplication.getDvrDataManager();
    }

    DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
    Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.x;
    int screenHeight = size.y;
    mDefaultRefreshRate = display.getRefreshRate();

    mOverlayRootView = (OverlayRootView) getLayoutInflater().inflate(R.layout.overlay_root_view, null, false);
    setContentView(R.layout.activity_tv);
    mTvView = (TunableTvView) findViewById(R.id.main_tunable_tv_view);
    int shrunkenTvViewHeight = getResources().getDimensionPixelSize(R.dimen.shrunken_tvview_height);
    mTvView.initialize((AppLayerTvView) findViewById(R.id.main_tv_view), false, screenHeight,
            shrunkenTvViewHeight);
    mTvView.setOnUnhandledInputEventListener(new OnUnhandledInputEventListener() {
        @Override
        public boolean onUnhandledInputEvent(InputEvent event) {
            if (isKeyEventBlocked()) {
                return true;
            }
            if (event instanceof KeyEvent) {
                KeyEvent keyEvent = (KeyEvent) event;
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.isLongPress()) {
                    if (onKeyLongPress(keyEvent.getKeyCode(), keyEvent)) {
                        return true;
                    }
                }
                if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    return onKeyUp(keyEvent.getKeyCode(), keyEvent);
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    return onKeyDown(keyEvent.getKeyCode(), keyEvent);
                }
            }
            return false;
        }
    });
    mTimeShiftManager = new TimeShiftManager(this, mTvView, mProgramDataManager, mTracker,
            new OnCurrentProgramUpdatedListener() {
                @Override
                public void onCurrentProgramUpdated(long channelId, Program program) {
                    updateMediaSession();
                    switch (mTimeShiftManager.getLastActionId()) {
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_REWIND:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_FAST_FORWARD:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_PREVIOUS:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_FORCE_SHOW);
                        break;
                    default:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_UPDATE_INFO);
                        break;
                    }
                }
            });

    mPipView = (TunableTvView) findViewById(R.id.pip_tunable_tv_view);
    mPipView.initialize((AppLayerTvView) findViewById(R.id.pip_tv_view), true, screenHeight,
            shrunkenTvViewHeight);

    if (!PermissionUtils.hasAccessWatchedHistory(this)) {
        WatchedHistoryManager watchedHistoryManager = new WatchedHistoryManager(getApplicationContext());
        watchedHistoryManager.start();
        mTvView.setWatchedHistoryManager(watchedHistoryManager);
    }
    mTvViewUiManager = new TvViewUiManager(this, mTvView, mPipView,
            (FrameLayout) findViewById(android.R.id.content), mTvOptionsManager);

    mPipView.setFixedSurfaceSize(screenWidth / 2, screenHeight / 2);
    mPipView.setBlockScreenType(TunableTvView.BLOCK_SCREEN_TYPE_SHRUNKEN_TV_VIEW);

    ViewGroup sceneContainer = (ViewGroup) findViewById(R.id.scene_container);
    mChannelBannerView = (ChannelBannerView) getLayoutInflater().inflate(R.layout.channel_banner,
            sceneContainer, false);
    mKeypadChannelSwitchView = (KeypadChannelSwitchView) getLayoutInflater()
            .inflate(R.layout.keypad_channel_switch, sceneContainer, false);
    InputBannerView inputBannerView = (InputBannerView) getLayoutInflater().inflate(R.layout.input_banner,
            sceneContainer, false);
    SelectInputView selectInputView = (SelectInputView) getLayoutInflater().inflate(R.layout.select_input,
            sceneContainer, false);
    selectInputView.setOnInputSelectedCallback(new OnInputSelectedCallback() {
        @Override
        public void onTunerInputSelected() {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            if (currentChannel != null && !currentChannel.isPassthrough()) {
                hideOverlays();
            } else {
                tuneToLastWatchedChannelForTunerInput();
            }
        }

        @Override
        public void onPassthroughInputSelected(TvInputInfo input) {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            String currentInputId = currentChannel == null ? null : currentChannel.getInputId();
            if (TextUtils.equals(input.getId(), currentInputId)) {
                hideOverlays();
            } else {
                tuneToChannel(Channel.createPassthroughChannel(input.getId()));
            }
        }

        private void hideOverlays() {
            getOverlayManager().hideOverlays(TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_DIALOG
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_SIDE_PANELS
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_PROGRAM_GUIDE
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_MENU
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_FRAGMENT);
        }
    });
    mSearchFragment = new ProgramGuideSearchFragment();
    mOverlayManager = new TvOverlayManager(this, mChannelTuner, mKeypadChannelSwitchView, mChannelBannerView,
            inputBannerView, selectInputView, sceneContainer, mSearchFragment);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mAudioFocusStatus = AudioManager.AUDIOFOCUS_LOSS;

    mMediaSession = new MediaSession(this, MEDIA_SESSION_TAG);
    mMediaSession.setCallback(new MediaSession.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
            // Consume the media button event here. Should not send it to other apps.
            return true;
        }
    });
    mMediaSession
            .setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mNowPlayingCardWidth = getResources().getDimensionPixelSize(R.dimen.notif_card_img_max_width);
    mNowPlayingCardHeight = getResources().getDimensionPixelSize(R.dimen.notif_card_img_height);

    mTvViewUiManager.restoreDisplayMode(false);
    if (!handleIntent(getIntent())) {
        finish();
        return;
    }

    mAudioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this,
            new AudioCapabilitiesReceiver.OnAc3PassthroughCapabilityChangeListener() {
                @Override
                public void onAc3PassthroughCapabilityChange(boolean capability) {
                    mAc3PassthroughSupported = capability;
                }
            });
    mAudioCapabilitiesReceiver.register();

    mAccessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
    mSendConfigInfoRecurringRunner = new RecurringRunner(this, TimeUnit.DAYS.toMillis(1),
            new SendConfigInfoRunnable(mTracker, mTvInputManagerHelper), null);
    mSendConfigInfoRecurringRunner.start();
    mChannelStatusRecurringRunner = SendChannelStatusRunnable.startChannelStatusRecurringRunner(this, mTracker,
            mChannelDataManager);

    // To avoid not updating Rating systems when changing language.
    mTvInputManagerHelper.getContentRatingsManager().update();

    initForTest();
}

From source file:com.miz.functions.MizLib.java

public static int getThumbnailSize(Context c) {
    final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
    final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

    WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
    Display d = window.getDefaultDisplay();

    Point size = new Point();
    d.getSize(size);//from ww  w .j  ava  2  s .co  m

    final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));

    if (numColumns > 0) {
        final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;

        if (columnWidth > 320)
            return 440;
        else if (columnWidth > 240)
            return 320;
        else if (columnWidth > 180)
            return 240;
    }

    return 180;
}

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

public void onCreate(Bundle savedInstanceState) {
    if (debugUsbComm) {
        logString = TAG + ": onCreate";
        Log.d(TAG, logString);//from  w  w w .  j a  v  a  2s  .  c o  m
        appendLog("debugUsbComm.txt", logString, false);
    }

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    camera = (SurfaceView) findViewById(R.id.smallcameraview);
    context = this.getApplicationContext();
    line1 = (TextView) findViewById(R.id.line1);
    line2 = (TextView) findViewById(R.id.line2);
    version = (TextView) findViewById(R.id.version);
    signWifi = (TextView) findViewById(R.id.advice);
    signStreaming = (TextView) findViewById(R.id.streaming);
    signInformation = (LinearLayout) findViewById(R.id.information);
    pulseAnimation = AnimationUtils.loadAnimation(this, R.anim.pulse);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

    settings.registerOnSharedPreferenceChangeListener(this);

    camera.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    holder = camera.getHolder();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "com.wheelphone.remotemini.wakelock");

    httpServer = new CustomHttpServer(8080, this.getApplicationContext(), handler);

    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPool.play(sampleId, 0.99f, 0.99f, 1, 0, 1);
        }
    });

    timerImg = new Timer();

    intent = new Intent(context, FrontImageActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //startActivity(intent);        

    // Query the QCAR initialization flags:
    mQCARFlags = getInitializationFlags();

    // Update the application status to start initializing application
    updateApplicationStatus(APPSTATUS_INIT_APP);

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    updateRendering(size.x, size.y);

    btnStart = (Button) findViewById(R.id.btnStart);

    //Make sure that the app stays open:
    getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    wheelphone = new WheelphoneRobot(getApplicationContext(), getIntent());
    wheelphone.enableSpeedControl();
    wheelphone.setWheelPhoneRobotListener(this);

}

From source file:de.ribeiro.android.gso.core.UntisProvider.java

/**
 * @param weekData WeekData in dem gesucht werden soll
 * @return Liefert den Point, der frei ist
 * @author Tobias Janssen Sucht in dem WeekData den letzten freien Platz
 *///from  w  w w . j  a v  a 2 s  .co  m
private static Point getLastFreePosition(WeekData weekData) {

    Point freeIndexPoint = new Point();
    Boolean success = false;
    for (int y = 0; y < weekData.timetable.length && !success; y++) {
        for (int x = 0; x < weekData.timetable[y].length && !success; x++) {
            if (weekData.timetable[y][x] == null) {
                freeIndexPoint.y = y;
                freeIndexPoint.x = x;
                success = true;
            }
        }
    }
    // TODO: exception wenn kein leerer eintrag gefunden wurde
    return freeIndexPoint;
}

From source file:com.miz.functions.MizLib.java

public static void resizeBitmapFileToCoverSize(Context c, String filepath) {

    final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
    final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

    WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
    Display d = window.getDefaultDisplay();

    Point size = new Point();
    d.getSize(size);//w  ww  .  ja  v a2s . com

    final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));

    if (numColumns > 0) {
        final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;

        int imageWidth = 0;

        if (columnWidth > 300)
            imageWidth = 500;
        else if (columnWidth > 240)
            imageWidth = 320;
        else if (columnWidth > 180)
            imageWidth = 240;
        else
            imageWidth = 180;

        if (new File(filepath).exists())
            try {
                Bitmap bm = decodeSampledBitmapFromFile(filepath, imageWidth, (int) (imageWidth * 1.5));
                bm = Bitmap.createScaledBitmap(bm, imageWidth, (int) (imageWidth * 1.5), true);
                FileOutputStream out = new FileOutputStream(filepath);
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.close();
                bm.recycle();
            } catch (Exception e) {
            }
    }
}

From source file:com.example.camera2apidemo.Camera2BasicFragment.java

/**   , ?
 * ??:// w  w  w.ja v  a  2s  .com
 * 1. ???, ?
 * 2. ????, ???
 * 3. ??, ?
 * Sets up member variables related to camera.     *
 * @param width  The width of available size for camera preview
 * @param height The height of available size for camera preview
 */
private void setUpCameraOutputs(int width, int height) {
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try { // ????
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

            checkCamera2Support(characteristics);
            // ???, ?(???)
            // We don't use a front facing camera in this sample.
            Integer facing = characteristics.get(LENS_FACING);
            if (facing != null && facing == LENS_FACING_FRONT) {
                continue;
            }

            //                ??
            StreamConfigurationMap map = characteristics.get(SCALER_STREAM_CONFIGURATION_MAP);
            if (map == null) {
                continue;
            }
            // For still image captures, we use the largest available size.
            // 
            // maxImagesImageReader??
            Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                    new CompareSizesByArea());
            mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG,
                    /*maxImages*/2);
            mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);

            // Find out if we need to swap dimension to get the preview size relative to sensor
            // coordinate.
            // ???(??, ""???ROTATION_90
            // ROTATION_270,?ROTATION_0ROTATION_180)
            int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            //noinspection ConstantConditions
            // ??(""?0, , ?90)
            // ?, ??, , 90, switch??
            mSensorOrientation = characteristics.get(SENSOR_ORIENTATION);
            boolean swappedDimensions = false;
            switch (displayRotation) {
            // ROTATION_0ROTATION_180??????
            // ?, ?90270, ??(?true)
            case Surface.ROTATION_0:
            case Surface.ROTATION_180:
                if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                    swappedDimensions = true;
                }
                break;
            case Surface.ROTATION_90:
            case Surface.ROTATION_270:
                if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                    swappedDimensions = true;
                }
                break;
            default:
                Log.e(TAG, "Display rotation is invalid: " + displayRotation);
            }
            // ???, 
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            // ?(), ??
            int rotatedPreviewWidth = width;
            int rotatedPreviewHeight = height;
            // ?(, ?(texture????))
            int maxPreviewWidth = displaySize.x;
            int maxPreviewHeight = displaySize.y;

            // ??, 
            if (swappedDimensions) {
                rotatedPreviewWidth = height;
                rotatedPreviewHeight = width;
                maxPreviewWidth = displaySize.y;
                maxPreviewHeight = displaySize.x;
            }
            // ??
            if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                maxPreviewWidth = MAX_PREVIEW_WIDTH;
            }

            if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                maxPreviewHeight = MAX_PREVIEW_HEIGHT;
            }

            // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
            // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
            // garbage capture data.
            // ?
            // ?:map.getOutputSizes(SurfaceTexture.class)SurfaceTexture?List
            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth,
                    rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest);

            // We fit the aspect ratio of TextureView to the size of preview we picked.
            // ????
            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                // ??(landscape)
                mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            } else {
                mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
            }

            // Check if the flash is supported.
            Boolean available = characteristics.get(FLASH_INFO_AVAILABLE);
            mFlashSupported = available == null ? false : available;

            mCameraId = cameraId;
            return;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        // Currently an NPE is thrown when the Camera2API is used but not supported on the
        // device this code runs.
        ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(),
                FRAGMENT_DIALOG);
    }
}