Android 6.0 Camera2 源码分析(1)不同的activity界面

Camera2中主要的activity

activity都在AnroidManifest.xml中有注册。我们先通过AndroidManifest.xml来大概的了解下都有哪些activity

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest  xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.camera2">

    <uses-sdk  android:minSdkVersion="19" android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.BIND_WALLPAPER" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.SET_WALLPAPER" />
    <uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_READ" />
    <uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_WRITE" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

    <supports-screens  android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="false" />

    <application  android:name="com.android.camera.app.CameraApp" android:hardwareAccelerated="true" android:icon="@mipmap/logo_camera_color_44in48dp" android:label="@string/app_name" android:largeHeap="true" android:restoreAnyVersion="true" android:supportsRtl="true" android:theme="@style/Theme.Camera" android:usesCleartextTraffic="false" >
        <activity  android:name="com.android.camera.CameraActivity" android:clearTaskOnLaunch="true" android:configChanges="orientation|screenSize|keyboardHidden" android:label="@string/app_name" android:launchMode="singleTask" android:taskAffinity="com.android.camera.CameraActivity" android:theme="@style/Theme.Camera" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data  android:name="com.android.keyguard.layout" android:resource="@layout/keyguard_widget" />
        </activity>

        <activity  android:name="com.android.camera.PermissionsActivity" android:configChanges="orientation|screenSize|keyboardHidden" android:label="@string/app_name" android:excludeFromRecents="true" android:parentActivityName="com.android.camera.CameraActivity" >
            <meta-data  android:name="android.support.PARENT_ACTIVITY" android:value="com.android.camera.CameraActivity" />
        </activity>

        <activity-alias  android:name="com.android.camera.CameraLauncher" android:label="@string/app_name" android:targetActivity="com.android.camera.CameraActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity  android:name="com.android.camera.CaptureActivity" android:label="@string/app_name" android:theme="@style/Theme.Camera" android:configChanges="orientation|screenSize|keyboardHidden" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <!-- Video camera and capture use the Camcorder label and icon. -->
        <activity-alias  android:name="com.android.camera.VideoCamera" android:label="@string/video_camera_label" android:targetActivity="com.android.camera.CaptureActivity">
            <intent-filter>
                <action android:name="android.media.action.VIDEO_CAMERA" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.media.action.VIDEO_CAPTURE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity-alias>

        <activity  android:name="com.android.camera.SecureCameraActivity" android:clearTaskOnLaunch="true" android:configChanges="orientation|screenSize|keyboardHidden" android:excludeFromRecents="true" android:label="@string/app_name" android:taskAffinity="com.android.camera.SecureCameraActivity" android:theme="@style/Theme.SecureCamera" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" >
            <intent-filter>
                <action android:name="android.media.action.STILL_IMAGE_CAMERA_SECURE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE_SECURE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data  android:name="com.android.keyguard.layout" android:resource="@layout/keyguard_widget" />
        </activity>

        <activity  android:name="com.android.camera.settings.CameraSettingsActivity" android:label="@string/mode_settings" android:theme="@style/Theme.CameraSettings" android:configChanges="keyboardHidden|orientation|screenSize">
        </activity>

        <receiver android:name="com.android.camera.DisableCameraReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <!-- UCamera Configure Start -->
       <activity  android:name="com.ucamera.uphoto.ImageEditControlActivity" android:label="@string/text_uphoto_label" android:launchMode="singleTop" android:screenOrientation="portrait" android:taskAffinity="com.ucamera.ucam.UPhoto" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SPRD_EDITOR" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>
            <!-- <intent-filter> <action android:name="android.intent.action.SEND" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.EDIT" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.CREATE_SHORTCUT" /> </intent-filter> -->
            <intent-filter>
                <action android:name="android.intent.action.UGALLERY_EDIT" />
                <data android:mimeType="image/*" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity  android:name="com.ucamera.ucomm.downloadcenter.DownloadCenterActivity" android:launchMode="singleTask" android:screenOrientation="portrait" />
        <activity  android:name="com.ucamera.ucomm.downloadcenter.DownloadTabActivity" android:launchMode="singleTask" android:screenOrientation="portrait" />
        <activity  android:name="com.ucamera.ucomm.puzzle.PuzzleActivity" android:launchMode="singleTop" android:screenOrientation="portrait" >
        </activity>
        <activity  android:name="com.ucamera.uphoto.exception.MailSenderActivity" android:theme="@android:style/Theme.NoDisplay" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.EMBED" />
            </intent-filter>
        </activity>
        <!-- UGallery -->
        <activity android:name="com.ucamera.uphoto.CropImage" />
        <!-- SPRD:fix bug533979 unmount SD card, imageGallery can not select photo -->
        <activity  android:name="com.ucamera.ugallery.ImageGallery" android:configChanges="orientation|keyboardHidden" android:label="@string/text_ugallery_name" android:launchMode="singleTop" android:screenOrientation="portrait" >
            <!-- <intent-filter> <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.OPENABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> <data android:mimeType="vnd.android.cursor.dir/image" /> </intent-filter> -->
        </activity>
        <activity  android:name="com.ucamera.ugallery.BaseImagePicker" android:configChanges="orientation|keyboardHidden" android:screenOrientation="portrait" />
        <activity  android:name="com.ucamera.ugallery.ViewImage" android:configChanges="orientation|keyboardHidden" >
            <intent-filter>
                <action android:name="android.intent.action.UGallery.ViewImage" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <!-- <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> -->
        </activity>
        <activity  android:name="com.ucamera.ugallery.DefaultImagePicker" android:screenOrientation="portrait" >
        </activity>
        <activity  android:name="com.ucamera.ucomm.puzzle.PuzzleImagePicker" android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.SPRD_PUZZLE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
         <activity  android:name="com.ucamera.ugallery.CollageSingleImagePicker" android:screenOrientation="portrait" >
        </activity>
        <activity  android:name="com.ucamera.ugallery.CropImage" android:configChanges="orientation|keyboardHidden" android:process=":CropImage" >
            <!-- fix bug462452 <intent-filter> <action android:name="com.android.camera.action.CROP" /> <data android:mimeType="image/*" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> -->
        </activity>
        <activity  android:name="com.ucamera.ugallery.preference.UGalleryPreferenceActivity" android:screenOrientation="portrait" />

        <activity android:name="com.ucamera.ugallery.CollageImagePickerActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />

        <activity android:name="com.ucamera.ugallery.panorama.UgalleryPanoramaActivity" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:screenOrientation="landscape">
        </activity>
        <activity android:name="com.ucamera.ugallery.Wallpaper" android:label="@string/ugallery_setas_wallpaper" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
            <!-- <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.ATTACH_DATA" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> -->
        </activity>

        <activity  android:name="com.ucamera.ugallery.video.MovieView" android:configChanges="orientation|screenSize" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
        </activity>

        <activity android:name = "com.ucamera.ugallery.MyFullDialogActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
        <activity android:name = "com.ucamera.ugallery.GifPlayerActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
        <activity android:name="com.ucamera.ugallery.MailSenderActivity" android:theme="@android:style/Theme.NoDisplay">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.EMBED" />
            </intent-filter>
        </activity>
        <!-- SNS -->
<!-- <activity -->
<!-- android:name="com.ucamera.ucomm.sns.ShareActivity" -->
<!-- android:configChanges="orientation|screenSize|keyboardHidden|navigation" -->
<!-- android:screenOrientation="portrait" -->
<!-- android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > -->
<!-- <intent-filter> -->
<!-- <action android:name="android.intent.action.UGALLERY_SHARE" /> -->

<!-- <data android:mimeType="image/*" /> -->

<!-- <category android:name="android.intent.category.DEFAULT" /> -->
<!-- </intent-filter> -->
<!-- </activity> -->
        <activity  android:name="com.ucamera.ucomm.sns.AccountsActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
<!-- <activity -->
<!-- android:name="com.tencent.tauth.AuthActivity" -->
<!-- android:launchMode="singleTask" -->
<!-- android:noHistory="true" > -->
<!-- <intent-filter> -->
<!-- <action android:name="android.intent.action.VIEW" /> -->
<!-- <category android:name="android.intent.category.DEFAULT" /> -->
<!-- <category android:name="android.intent.category.BROWSABLE" /> -->
<!-- <data android:scheme="tencent100247210" />100380359 100381104 222222 -->
<!-- </intent-filter> -->
<!-- </activity> -->
        <activity android:name="com.tencent.connect.common.AssistActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:screenOrientation="portrait"/>
        <activity android:name="com.tencent.plus.ImageActivity" />
        <!-- fix bug527736 Some Activity about UCamera lacks method of checkpermission -->
        <activity  android:name="com.ucamera.ucam.modules.ugif.GifBrowser" android:launchMode="singleTop" android:screenOrientation="portrait" />
        <activity  android:name="com.ucamera.ucam.modules.ugif.GifPlayActivity" android:label="@string/text_gif_play_label" android:screenOrientation="portrait" >
        </activity>
        <activity  android:name="com.ucamera.ucam.modules.ugif.edit.GifEditActivity" android:configChanges="locale|layoutDirection|orientation" android:launchMode="singleTop" android:screenOrientation="portrait" />
        <provider  android:name="com.ucamera.ugallery.provider.UCamDataProvider" android:authorities="com.ucamera.uphoto.provider" android:grantUriPermissions="true" />
        <!-- UGallery END -->

    </application>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.READ_LOGS" />
<!-- UCamera Configure end -->

</manifest>

主要的activity

从上面的AndroidManifest.xml中可以看到,主要包括的activity:

  1. CameraActivity
  2. PermissionsActivity
  3. CaptureActivity
  4. VideoCamera
  5. SecureCameraActivity
  6. CameraSettingsActivity
  7. ImageEditControlActivity
  8. 以及部分ucamera中的activity,这里不做分析

不同activity的主要功能

1. CameraActivity

相机的主界面,我们通过launcher进入camera后,展现给我们的相机预览,录像预览界面。后面会详细分析。此处暂时pass

2.PermissionsActivity

顾名思义,主要是为了设置权限的界面。
关于PermissionsActivity的调用:
在CameraActivity.java中,在进入相机时,系统会首先check 权限是否ok。
onCreateTasks()

    @Override
    public void onCreateTasks(Bundle state) {
        Log.i(TAG, "onCreateTasks start!");

        UiUtils.initialize(this);

        Profile profile = mProfiler.create("CameraActivity.onCreateTasks").start();
        CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_START);
        if (UCamUtill.isTimeStampEnable()) {
            ImageProcessJni.SetJNISOPath("/system/lib/");
        }
        mOnCreateTime = System.currentTimeMillis();
        mAppContext = getApplicationContext();
        mMainHandler = new MainHandler(this, getMainLooper());
        mLocationManager = new LocationManager(mAppContext);
        mOrientationManager = new OrientationManagerImpl(this, mMainHandler);
        mSettingsManager = getServices().getSettingsManager();
        mSoundPlayer = new SoundPlayer(mAppContext);
        mFeatureConfig = OneCameraFeatureConfigCreator.createDefault(getContentResolver(),
                getServices().getMemoryManager());
        mFatalErrorHandler = new FatalErrorHandlerImpl(this);
        if (!isCaptureIntent()) {
            Log.d(TAG,"checkPermissions start");
            //判断权限,是否打开PermissionsActivity.java
            checkPermissions();
            if (!mHasCriticalPermissions) {
                Log.v(TAG, "onCreate: Missing critical permissions.");
                finish();
                return;
            }
        }
        profile.mark();

onResumeTasks()

    @Override
    public void onResumeTasks() {
        Log.i(TAG, "onResumeTasks start!");

        mPaused = false;
        //判断权限。
        checkPermissions();
        if (!mHasCriticalPermissions) {
            Log.i(TAG, "onResume: Missing critical permissions.");
            /** * SPRD:fix bug519999 Create header photo, pop permission error * original code * finish(); */
            return;
        }
  private void checkPermissions() {
        if (!ApiHelper.isMOrHigher()) {
            Log.v(TAG, "not running on M, skipping permission checks");
            mHasCriticalPermissions = true;
            return;
        }

        if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            mHasCriticalPermissions = true;
        } else {
            mHasCriticalPermissions = false;
        }
        Log.d(TAG,"checkPermissions mHasCriticalPermissions is "+mHasCriticalPermissions);

        if ((isSupportGps && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                !mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, Keys.KEY_HAS_SEEN_PERMISSIONS_DIALOGS)) ||
                !mHasCriticalPermissions) {// SRPD:fix for bug 502029 after location feature disabled ,it shows the location permission notify
            //SPRD:fix bug501493,502701,498680,499555 problem caused by permission strategy
            Intent cameraIntent = getIntent();
            Bundle data = new Bundle();
            data.putParcelable("cameraIntent", cameraIntent);
            Intent intent = new Intent(this, PermissionsActivity.class);
            /* SPRD:fix bug498680 Open camera from contact,it shows modelistview @{ */
            //intent.setAction(getIntent().getAction());
            intent.putExtras(data);
            /* }@ */
            /*SPRD:fix bug519999 Create header photo, pop permission error*/
            if (!isCaptureIntent()) {
                Log.d(TAG,"start PermissionsActivity from 0");
                //需要设置权限,打开PermissionsAcitivity.java,关闭CameraActivity
                startActivity(intent);
                finish();
            } else {
                Log.d(TAG,"start PermissionsActivity from 1");
                startActivityForResult(intent,1);
            }
        }
    }

PermissionsActivity.java源码分析

package com.android.camera;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import com.android.camera.app.CameraServicesImpl;
import com.android.camera.debug.Log;
import com.android.camera.settings.Keys;
import com.android.camera.settings.SettingsManager;
import com.android.camera.util.QuickActivity;
import com.android.camera2.R;

/** * Activity that shows permissions request dialogs and handles lack of critical permissions. */
public class PermissionsActivity extends QuickActivity {
    private static final Log.Tag TAG = new Log.Tag("PermissionsActivity");

    private static int PERMISSION_REQUEST_CODE = 1;
    private static int RESULT_CODE_OK = 1;
    private static int RESULT_CODE_FAILED = 2;

    private int mIndexPermissionRequestCamera;
    private int mIndexPermissionRequestMicrophone;
    private int mIndexPermissionRequestLocation;
    private int mIndexPermissionRequestStorage;
    private boolean mShouldRequestCameraPermission;
    private boolean mShouldRequestMicrophonePermission;
    private boolean mShouldRequestLocationPermission;
    private boolean mShouldRequestStoragePermission;
    private int mNumPermissionsToRequest;
    private boolean mFlagHasCameraPermission;
    private boolean mFlagHasMicrophonePermission;
    private boolean mFlagHasStoragePermission;
    private SettingsManager mSettingsManager;
    private String cameraIntentAction;

    /** * Close activity when secure app passes lock screen or screen turns * off. */
    private final BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          Log.v(TAG, "received intent, finishing: " + intent.getAction());
          finish();
        }
    };

    @Override
    protected void onCreateTasks(Bundle savedInstanceState) {
        setContentView(R.layout.permissions);
        mSettingsManager = CameraServicesImpl.instance().getSettingsManager();

        // Filter for screen off so that we can finish permissions activity
        // when screen is off.
        IntentFilter filter_screen_off = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mShutdownReceiver, filter_screen_off);

        // Filter for phone unlock so that we can finish permissions activity
        // via this UI path:
        // 1. from secure lock screen, user starts secure camera
        // 2. user presses home button
        // 3. user unlocks phone
        IntentFilter filter_user_unlock = new IntentFilter(Intent.ACTION_USER_PRESENT);
        registerReceiver(mShutdownReceiver, filter_user_unlock);

        Window win = getWindow();
        if (isKeyguardLocked()) {
            win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        } else {
            win.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        }
        //SPRD:fix bug501493,502701,498680,499555 problem caused by permission strategy
        Intent cameraIntent = (Intent)getIntent().getParcelableExtra("cameraIntent");
        cameraIntentAction = cameraIntent.getAction();

        // SPRD Bug:508576 The dialog is created repeatly when rotating the screen.
        mNumPermissionsToRequest = 0;
        Log.d(TAG,"onCreateTasks start ");
        checkPermissions();
    }

    @Override
    protected void onResumeTasks() {
        /* * SPRD Bug:508576 The dialog is created repeatly when rotating the screen. @{ * Original Android code: mNumPermissionsToRequest = 0; checkPermissions(); */
        /* @} */
    }

    @Override
    protected void onDestroyTasks() {
        Log.v(TAG, "onDestroy: unregistering receivers");
        unregisterReceiver(mShutdownReceiver);
    }

    private void checkPermissions() {
        if (checkSelfPermission(Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            mNumPermissionsToRequest++;
            mShouldRequestCameraPermission = true;
        } else {
            mFlagHasCameraPermission = true;
        }

        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            mNumPermissionsToRequest++;
            mShouldRequestMicrophonePermission = true;
        } else {
            mFlagHasMicrophonePermission = true;
        }

        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            mNumPermissionsToRequest++;
            mShouldRequestStoragePermission = true;
        } else {
            mFlagHasStoragePermission = true;
        }

/* SRPD:fix for bug 502029 after location feature disabled ,it shows the location permission notify if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { mNumPermissionsToRequest++; mShouldRequestLocationPermission = true; } */

        if (mNumPermissionsToRequest != 0) {
            /* SPRD:fix bug519999 Create header photo, pop permission error * original code * if (!isKeyguardLocked() && !mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, * Keys.KEY_HAS_SEEN_PERMISSIONS_DIALOGS)) { */
            if (!isKeyguardLocked()) {
                buildPermissionsRequest();
            } else {
                // Permissions dialog has already been shown, or we're on
                // lockscreen, and we're still missing permissions.
                handlePermissionsFailure();
            }
        } else {
            handlePermissionsSuccess();
        }
    }

    private void buildPermissionsRequest() {
        String[] permissionsToRequest = new String[mNumPermissionsToRequest];
        int permissionsRequestIndex = 0;

        if (mShouldRequestCameraPermission) {
            permissionsToRequest[permissionsRequestIndex] = Manifest.permission.CAMERA;
            mIndexPermissionRequestCamera = permissionsRequestIndex;
            permissionsRequestIndex++;
        }
        if (mShouldRequestMicrophonePermission) {
            permissionsToRequest[permissionsRequestIndex] = Manifest.permission.RECORD_AUDIO;
            mIndexPermissionRequestMicrophone = permissionsRequestIndex;
            permissionsRequestIndex++;
        }
        if (mShouldRequestStoragePermission) {
            permissionsToRequest[permissionsRequestIndex] = Manifest.permission.READ_EXTERNAL_STORAGE;
            mIndexPermissionRequestStorage = permissionsRequestIndex;
            permissionsRequestIndex++;
        }
        if (mShouldRequestLocationPermission) {
            permissionsToRequest[permissionsRequestIndex] = Manifest.permission.ACCESS_COARSE_LOCATION;
            mIndexPermissionRequestLocation = permissionsRequestIndex;
        }

        Log.v(TAG, "requestPermissions count: " + permissionsToRequest.length);
        requestPermissions(permissionsToRequest, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        Log.v(TAG, "onPermissionsResult counts: " + permissions.length + ":" + grantResults.length);
        mSettingsManager.set(
                SettingsManager.SCOPE_GLOBAL,
                Keys.KEY_HAS_SEEN_PERMISSIONS_DIALOGS,
                true);

        if (mShouldRequestCameraPermission) {
            if (grantResults.length > 0 && grantResults[mIndexPermissionRequestCamera] ==
                    PackageManager.PERMISSION_GRANTED) {
                mFlagHasCameraPermission = true;
            } else {
                handlePermissionsFailure();
            }
        }
        if (mShouldRequestMicrophonePermission) {
            if (grantResults.length > 0 && grantResults[mIndexPermissionRequestMicrophone] ==
                    PackageManager.PERMISSION_GRANTED) {
                mFlagHasMicrophonePermission = true;
            } else {
                handlePermissionsFailure();
            }
        }
        if (mShouldRequestStoragePermission) {
            if (grantResults.length > 0 && grantResults[mIndexPermissionRequestStorage] ==
                    PackageManager.PERMISSION_GRANTED) {
                mFlagHasStoragePermission = true;
            } else {
                handlePermissionsFailure();
            }
        }

        if (mShouldRequestLocationPermission) {
            if (grantResults.length > 0 && grantResults[mIndexPermissionRequestLocation] ==
                    PackageManager.PERMISSION_GRANTED) {
                // Do nothing
            } else {
                // Do nothing
            }
        }

        if (mFlagHasCameraPermission && mFlagHasMicrophonePermission && mFlagHasStoragePermission) {
            handlePermissionsSuccess();
        }
    }

    private void handlePermissionsSuccess() {
        //SPRD:fix bug519999 Create header photo, pop permission error
        if (!isCaptureIntent()) {
            Intent intent = new Intent(this, CameraActivity.class);
            startActivity(intent);
        } else {
            setResult(RESULT_OK);
        }
        finish();
    }

    private void handlePermissionsFailure() {
        new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.camera_error_title))
                .setMessage(getResources().getString(R.string.error_permissions))
                .setCancelable(false)
                .setOnKeyListener(new Dialog.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            finish();
                        }
                        return true;
                    }
                })
                .setPositiveButton(getResources().getString(R.string.dialog_dismiss),
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (isCaptureIntent()) {
                            setResult(RESULT_CANCELED);
                        }
                        finish();
                    }
                })
                .show();
    }

    //SPRD:fix bug501493,502701,498680,499555 problem caused by permission strategy
    private boolean isCaptureIntent() {
        if (MediaStore.ACTION_VIDEO_CAPTURE.equals(cameraIntentAction)
                || MediaStore.ACTION_IMAGE_CAPTURE.equals(cameraIntentAction)
                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(cameraIntentAction)) {
            return true;
        } else {
            return false;
        }
    }
}

这个activity很好理解,最后是申请权限成功工作handlePermissionsSuccess重启启动CameraActivity

    private void handlePermissionsSuccess() {
        //SPRD:fix bug519999 Create header photo, pop permission error
        if (!isCaptureIntent()) {
            Intent intent = new Intent(this, CameraActivity.class);
            startActivity(intent);
        } else {
            setResult(RESULT_OK);
        }
        finish();
    }

CaptureActivity

此界面在AndroidManifest.xml中的注册信息如下:

        <activity  android:name="com.android.camera.CaptureActivity" android:label="@string/app_name" android:theme="@style/Theme.Camera" android:configChanges="orientation|screenSize|keyboardHidden" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

android.media.action.IMAGE_CAPTURE
主要是实现第三方调用相机拍照的功能。

        Intent intent = null;
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, RESULT_CAMERA_ONLY);

在onActivityResult中接收:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK)
        return;
    switch (requestCode) {
        case RESULT_CAMERA_ONLY: {
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                mImage.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        break;
    }
}

VideoCamera

        <!-- Video camera and capture use the Camcorder label and icon. -->
        <activity-alias  android:name="com.android.camera.VideoCamera" android:label="@string/video_camera_label" android:targetActivity="com.android.camera.CaptureActivity">
            <intent-filter>
                <action android:name="android.media.action.VIDEO_CAMERA" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.media.action.VIDEO_CAPTURE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity-alias>

和上面的相同也是提供第三方调用录像的接口。

SecureCameraActivity

        <activity  android:name="com.android.camera.SecureCameraActivity" android:clearTaskOnLaunch="true" android:configChanges="orientation|screenSize|keyboardHidden" android:excludeFromRecents="true" android:label="@string/app_name" android:taskAffinity="com.android.camera.SecureCameraActivity" android:theme="@style/Theme.SecureCamera" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" >
            <intent-filter>
                <action android:name="android.media.action.STILL_IMAGE_CAMERA_SECURE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE_SECURE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data  android:name="com.android.keyguard.layout" android:resource="@layout/keyguard_widget" />
        </activity>

在锁屏状态下,调用相机入口。

CameraSettingsActivity

有关相机设置的界面

ImageEditControlActivity 以及部分Ucamera的界面

ucamera的入口。

    原文作者:Android源码分析
    原文地址: https://blog.csdn.net/wangjicong_215/article/details/73278757
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞