Example usage for android.app Activity getSystemService

List of usage examples for android.app Activity getSystemService

Introduction

In this page you can find the example usage for android.app Activity getSystemService.

Prototype

@Override
    public Object getSystemService(@ServiceName @NonNull String name) 

Source Link

Usage

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void lockOrientation(Activity activity) {
    if (activity == null || prevOrientation != -10) {
        return;//from w ww . ja  va2 s . c om
    }
    try {
        prevOrientation = activity.getRequestedOrientation();
        WindowManager manager = (WindowManager) activity.getSystemService(Activity.WINDOW_SERVICE);
        if (manager != null && manager.getDefaultDisplay() != null) {
            int rotation = manager.getDefaultDisplay().getRotation();
            int orientation = activity.getResources().getConfiguration().orientation;

            if (rotation == Surface.ROTATION_270) {
                if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                }
            } else if (rotation == Surface.ROTATION_90) {
                if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                } else {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else if (rotation == Surface.ROTATION_0) {
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            } else {
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                } else {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                }
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:com.android.rahul.myselfieapp.Fragment.CamVideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//*  w  ww.  j  ava2  s  .c o m*/
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[0];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } 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);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}

From source file:com.example.android.camera2basic.Fragment.Camera2BasicFragment.java

/**
 * Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
 *///from   w  ww.j  ava  2  s  . c  om
private void openCamera(int width, int height) {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestCameraPermission();
        return;
    }
    setUpCameraOutputs(width, height);
    configureTransform(width, height);

    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:com.pvjunkies.fieldcam.CameraFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *///from www.  ja va2  s  .c o m
@SuppressWarnings("MissingPermission")
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[0];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        if (map == null) {
            throw new RuntimeException("Cannot get available preview/video sizes");
        }
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } 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);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}

From source file:com.example.android.camera2basic.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *///from  w w  w  .j  a  v  a2s  . com
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[0];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } 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);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}

From source file:com.mebene.ACHud.Camera2VideoFragment2.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 */// w ww .ja va2s.  co  m
@SuppressWarnings("MissingPermission")
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[0];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        if (map == null) {
            throw new RuntimeException("Cannot get available preview/video sizes");
        }
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } 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);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}

From source file:com.tenth.space.ui.fragment.HomeFragment.java

private void openCamera(int width, int height) {
    //        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
    //                ){
    //            new AlertDialog.Builder(getActivity(),AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
    //            .setTitle("???")
    //            .setPositiveButton("", new DialogInterface.OnClickListener() {
    //                 @Override
    //                public void onClick(DialogInterface dialog, int which) {
    //                    Log.i("GTAG","?");
    //                    requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.LOCATION_HARDWARE},REQUEST_CAMERA_PERMISSION);
    //                    requestPermissions(new String[]{Manifest.permission.LOCATION_HARDWARE},2);
    //                    ToastUtils.show("???");
    //                }
    //            })
    //            .setNegativeButton("?",null)
    //            .create()
    //            .show();
    //        }//  w  ww  .j a va  2s.  c  o m
    setUpCameraOutputs(width, height);
    configureTransform(width, height);
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        manager.openCamera("1", mStateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyAdvShareFragment.java

private void shareFingerprint(boolean toClipboard) {
    Activity activity = getActivity();
    if (activity == null || mFingerprint == null) {
        return;//from   w  ww . j  av  a 2  s  . c o m
    }

    String content;
    String fingerprint = KeyFormattingUtils.convertFingerprintToHex(mFingerprint);
    if (!toClipboard) {
        content = Constants.FINGERPRINT_SCHEME + ":" + fingerprint;
    } else {
        content = fingerprint;
    }

    if (toClipboard) {
        ClipboardManager clipMan = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipMan == null) {
            Notify.create(activity, R.string.error_clipboard_copy, Style.ERROR);
            return;
        }

        ClipData clip = ClipData.newPlainText(Constants.CLIPBOARD_LABEL, content);
        clipMan.setPrimaryClip(clip);

        Notify.create(activity, R.string.fingerprint_copied_to_clipboard, Notify.Style.OK).show();
        return;
    }

    // let user choose application
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, content);
    sendIntent.setType("text/plain");

    String title = getString(R.string.title_share_fingerprint_with);
    Intent shareChooser = Intent.createChooser(sendIntent, title);

    startActivity(shareChooser);
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyAdvShareFragment.java

private void shareKey(boolean toClipboard) {
    Activity activity = getActivity();
    if (activity == null || mFingerprint == null) {
        return;//from w ww  . ja  va2s.  c o m
    }
    ProviderHelper providerHelper = new ProviderHelper(activity);

    try {
        String content = providerHelper
                .getKeyRingAsArmoredString(KeychainContract.KeyRingData.buildPublicKeyRingUri(mDataUri));

        if (toClipboard) {
            ClipboardManager clipMan = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipMan == null) {
                Notify.create(activity, R.string.error_clipboard_copy, Style.ERROR);
                return;
            }

            ClipData clip = ClipData.newPlainText(Constants.CLIPBOARD_LABEL, content);
            clipMan.setPrimaryClip(clip);

            Notify.create(activity, R.string.key_copied_to_clipboard, Notify.Style.OK).show();
            return;
        }

        // let user choose application
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType(Constants.MIME_TYPE_KEYS);

        // NOTE: Don't use Intent.EXTRA_TEXT to send the key
        // better send it via a Uri!
        // example: Bluetooth Share will convert text/plain sent via Intent.EXTRA_TEXT to HTML
        try {
            TemporaryFileProvider shareFileProv = new TemporaryFileProvider();

            String filename = KeyFormattingUtils.convertFingerprintToHex(mFingerprint);
            OpenPgpUtils.UserId mainUserId = KeyRing.splitUserId(mUserId);
            if (mainUserId.name != null) {
                filename = mainUserId.name;
            }
            Uri contentUri = TemporaryFileProvider.createFile(activity,
                    filename + Constants.FILE_EXTENSION_ASC);

            BufferedWriter contentWriter = new BufferedWriter(new OutputStreamWriter(
                    new ParcelFileDescriptor.AutoCloseOutputStream(shareFileProv.openFile(contentUri, "w"))));
            contentWriter.write(content);
            contentWriter.close();

            sendIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        } catch (FileNotFoundException e) {
            Log.e(Constants.TAG, "Error creating temporary key share file!", e);
            // no need for a snackbar because one sharing option doesn't work
            // Notify.create(getActivity(), R.string.error_temp_file, Notify.Style.ERROR).show();
        }

        String title = getString(R.string.title_share_key);
        Intent shareChooser = Intent.createChooser(sendIntent, title);

        startActivity(shareChooser);
    } catch (PgpGeneralException | IOException e) {
        Log.e(Constants.TAG, "error processing key!", e);
        Notify.create(activity, R.string.error_key_processing, Notify.Style.ERROR).show();
    } catch (ProviderHelper.NotFoundException e) {
        Log.e(Constants.TAG, "key not found!", e);
        Notify.create(activity, R.string.error_key_not_found, Notify.Style.ERROR).show();
    }
}

From source file:com.mebene.ACHud.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *///  w  w w  .  ja  v a2  s  . c  om
@SuppressWarnings("MissingPermission")
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[0];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        //mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        if (map == null) {
            throw new RuntimeException("Cannot get available preview/video sizes");
        }
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        /*
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
        mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        */

        mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());

        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } 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);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}