android7.1的SnapdragonCamera之CameraActivity逻辑流程分析整体

不积跬步无以至千里
“一花一世界,一树一乾坤,一草一天堂,一木一浮生”,这句话告诉我们通过一小部分可以知道整个整体,同样的Camera也一样,本文主要分析这个CameraActivity。
其实我发现AndroidMainfest.xml中,启动Activity就是CameraActivity的别名的CameraLauncher,如下图:
这里写图片描述
下面看一下这个CameraActivity的整个生命周期(代码的逻辑,我通过加注释给大家解释一下)。

onCreate方法

    public void onCreate(Bundle state) {
        super.onCreate(state);
        //检查权限,如果权限没检查过,或者没有批准的权限直接关闭。另说一嘴,大家都知道吗?android7.1又对权限做了新的处理。
        if (checkPermissions() || !mHasCriticalPermissions) {
            Log.v(TAG, "onCreate: Missing critical permissions.");
            //关闭本Activity,即跳出整个程序
            finish();
            return;
        }
         // Check if this is in the secure camera mode.检查是否为安全相机模式
        Intent intent = getIntent();
        String action = intent.getAction();
        if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)
                || ACTION_IMAGE_CAPTURE_SECURE.equals(action)
                || intent.getComponent().getClassName().equals(GESTURE_CAMERA_NAME)) {
            mSecureCamera = true;
        } else {
            mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
        }
        //根据相机是不是安全相机模式做处理
        if (mSecureCamera) {
            // Change the window flags so that secure camera can show when locked 当被锁住时,为安全模式时,改变窗口。
            Window win = getWindow();
            WindowManager.LayoutParams params = win.getAttributes();
            params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
            if (intent.getComponent().getClassName().equals(GESTURE_CAMERA_NAME)) {
                params.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
                //获取唤醒锁
                PowerManager pm = ((PowerManager) getSystemService(POWER_SERVICE));
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                mWakeLock.acquire();
                Log.d(TAG, "acquire wake lock");
            }
            win.setAttributes(params);
        }
        GcamHelper.init(getContentResolver());
        //设置actionBar
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.camera_filmstrip);
        //为ActionBa设置菜单可见监听
        mActionBar = getActionBar();
        mActionBar.addOnMenuVisibilityListener(this);
        //当大于4.3版本,设置窗口的旋转动画
        if (ApiHelper.HAS_ROTATION_ANIMATION) {
            setRotationAnimation();
        }
        //声明一个主线程的Handler,主要用于ActionBar的隐藏和显示
        mMainHandler = new MainHandler(getMainLooper());
        //关联控件
 mAboveFilmstripControlLayout =
                (FrameLayout) findViewById(R.id.camera_above_filmstrip_layout);
        mAboveFilmstripControlLayout。setFitsSystemWindows(true);
mAboveFilmstripControlLayout。setFitsSystemWindows(true);
this.setSystemBarsVisibility(false);
        mPanoramaManager = AppManagerFactory.getInstance(this)
                。getPanoramaStitchingManager();
        mPlaceholderManager = AppManagerFactory.getInstance(this)
                。getGcamProcessingManager();
                //添加图片加载监听
        mPanoramaManager。addTaskListener(mStitchingListener);
        mPlaceholderManager。addTaskListener(mPlaceholderListener);
         LayoutInflater inflater = getLayoutInflater();
        View rootLayout = inflater。inflate(R。layout。camera, null, false);
        mCameraRootFrame = (FrameLayout)rootLayout。findViewById(R。id。camera_root_frame);
        mCameraPhotoModuleRootView = rootLayout。findViewById(R。id。camera_photo_root);
        mCameraVideoModuleRootView = rootLayout。findViewById(R。id。camera_video_root);
        mCameraPanoModuleRootView = rootLayout。findViewById(R。id。camera_pano_root);
        mPanoStitchingPanel = findViewById(R。id。pano_stitching_progress_panel);
        mBottomProgress = (ProgressBar) findViewById(R。id。pano_stitching_progress_bar);
        mCameraPreviewData = new CameraPreviewData(rootLayout,
                FilmStripView。ImageData。SIZE_FULL,
                FilmStripView。ImageData。SIZE_FULL);
        // Put a CameraPreviewData at the first position
        mWrappedDataAdapter = new FixedFirstDataAdapter(
                new CameraDataAdapter(new ColorDrawable(
                        getResources()。getColor(R。color.photo_placeholder))),
                mCameraPreviewData);
        mFilmStripView = (FilmStripView) findViewById(R。id.filmstrip_view);
        mFilmStripView。setViewGap(
                getResources()。getDimensionPixelSize(R。dimen.camera_film_strip_gap));
        mPanoramaViewHelper = new PanoramaViewHelper(this);
        mPanoramaViewHelper。onCreate();
        mFilmStripView。setPanoramaViewHelper(mPanoramaViewHelper);
        // Set up the camera preview first so the preview shows up ASAP
        mFilmStripView。setListener(mFilmStripListener);
        //获取当前的拍照模式:视频、照相
        int moduleIndex = -1;
        if (MediaStore。INTENT_ACTION_VIDEO_CAMERA。equals(getIntent()。getAction())
                || MediaStore。ACTION_VIDEO_CAPTURE。equals(getIntent()。getAction())) {
            moduleIndex = ModuleSwitcher。VIDEO_MODULE_INDEX;
        } else if (MediaStore。INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent()。getAction())
                || MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE。equals(getIntent()
                        。getAction())) {
            moduleIndex = ModuleSwitcher。PHOTO_MODULE_INDEX;
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            if (prefs.getInt(CameraSettings.KEY_STARTUP_MODULE_INDEX, -1)
                        == ModuleSwitcher.GCAM_MODULE_INDEX && GcamHelper.hasGcamCapture()) {
                moduleIndex = ModuleSwitcher.GCAM_MODULE_INDEX;
            }
        } else if (MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
            moduleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
        } else {
            // If the activity has not been started using an explicit intent,
            // read the module index from the last time the user changed modes
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            moduleIndex = prefs.getInt(CameraSettings.KEY_STARTUP_MODULE_INDEX, -1);
            if ((moduleIndex == ModuleSwitcher.GCAM_MODULE_INDEX &&
                    !GcamHelper.hasGcamCapture()) || moduleIndex < 0) {
                moduleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
            }
        }
        //设置重力感应监听
        mOrientationListener = new MyOrientationEventListener(this);
        //根据上面获取、判断的模式,去设置界面的显示等等。
        setModuleFromIndex(moduleIndex);
        //根据是不是安全相机来处理
if (!mSecureCamera) {
            mDataAdapter = mWrappedDataAdapter;
            mFilmStripView。setDataAdapter(mDataAdapter);
            if (!isCaptureIntent()) {
                mDataAdapter。requestLoad(getContentResolver());
                mDataRequested = true;
            }
        } else {
            // Put a lock placeholder as the last image by setting its date to
            // 0.
            //点击照片跳转意图
            ImageView v = (ImageView) getLayoutInflater().inflate(
                    R.layout.secure_album_placeholder, null);
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
                                UsageStatistics.ACTION_GALLERY, null);
                //跳转到相册        startActivity(IntentHelper.getGalleryIntent(CameraActivity.this));
                    } catch (ActivityNotFoundException e) {
                        Log.w(TAG, "Failed to launch gallery activity, closing");
                    }
                    finish();
                }
            });
            mDataAdapter = new FixedLastDataAdapter(
                    mWrappedDataAdapter,
                    new SimpleViewData(
                            v,
                            v.getDrawable().getIntrinsicWidth(),
                            v.getDrawable().getIntrinsicHeight(),
                            0, 0));
            // Flush out all the original data.
            mDataAdapter.flush();
            mFilmStripView.setDataAdapter(mDataAdapter);
        }
        //设置nfc
        setupNfcBeamPush();
        //设置观察者,来分别观察图片的变化和视频资源的变化
        mLocalImagesObserver = new LocalMediaObserver();
        mLocalVideosObserver = new LocalMediaObserver();
        getContentResolver().registerContentObserver(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
                mLocalImagesObserver);
        getContentResolver().registerContentObserver(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true,
                mLocalVideosObserver);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        mDeveloperMenuEnabled = prefs.getBoolean(CameraSettings.KEY_DEVELOPER_MENU, false);
        //设置窗口大小
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;

        int lower = Math.min(width, height);

        int offset = lower * 10 / 100;
        SETTING_LIST_WIDTH_1 = lower / 2 + offset;
        SETTING_LIST_WIDTH_2 = lower / 2 - offset;
        //注册关于sd的挂载的广播
        registerSDcardMountedReceiver();
    }

onStart方法:

@Override
    public void onStart() {
        super.onStart();
        //开启添加图片、视频的service
        bindMediaSaveService();
        mPanoramaViewHelper.onStart();
    }

onResume方法:

@Override
    public void onResume() {
        //权限检测
        if (checkPermissions() || !mHasCriticalPermissions) {
            super。onResume();
            Log.v(TAG, "onResume: Missing critical permissions.");
            finish();
            return;
        }

        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
                UsageStatistics.ACTION_FOREGROUNDED, this.getClass().getSimpleName());
        mOrientationListener.enable();
        mCurrentModule.onResumeBeforeSuper();
        super.onResume();
        mCurrentModule.onResumeAfterSuper();
        //设置预览画面能否滑动
        setSwipingEnabled(true);

        if (mResetToPreviewOnResume) {
            // Go to the preview on resume.
            mFilmStripView.getController().goToFirstItem();
        }
        // Default is showing the preview, unless disabled by explicitly
        // starting an activity we want to return from to the filmstrip rather
        // than the preview.
        mResetToPreviewOnResume = true;
        //查看图片和视频资源有无变化,有则重新加载
        if (mLocalVideosObserver.isMediaDataChangedDuringPause()
                || mLocalImagesObserver.isMediaDataChangedDuringPause()) {
            if (!mSecureCamera) {
                // If it's secure camera, requestLoad() should not be called
                // as it will load all the data.
                mDataAdapter.requestLoad(getContentResolver());
                mThumbnailDrawable = null;
            }
        }
        //重置观察者标志位
        mLocalImagesObserver.setActivityPaused(false);
        mLocalVideosObserver.setActivityPaused(false);

        //This is a temporal solution to share LED resource
        //as Android doesn’t have any default intent to share the state.
        // if the led flash light is open, turn it off
        Log.d(TAG, "send the turn off Flashlight broadcast");
        //关闭闪光灯
        Intent intent = new Intent("org.codeaurora.snapcam.action.CLOSE_FLASHLIGHT");
        intent.putExtra("camera_led", true);
        sendBroadcast(intent);
    }

onPause方法:

    @Override
    public void onPause() {
        // Delete photos that are pending deletion
        //删除照片时正好界面pause了的处理
        performDeletion();
        //关闭重力传感器监听
        mOrientationListener.disable();
        mCurrentModule.onPauseBeforeSuper();
        super.onPause();
        mCurrentModule.onPauseAfterSuper();
        //设置观察者的标志位
        mLocalImagesObserver.setActivityPaused(true);
        mLocalVideosObserver.setActivityPaused(true);
    }

onStop方法:

    @Override
    protected void onStop() {
        super.onStop();
        mPanoramaViewHelper.onStop();
        //断开存储视频、图片的service
        unbindMediaSaveService();
    }

onDestory方法:

@Override
    public void onDestroy() {
        //释放唤醒锁
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
            Log.d(TAG, "wake lock release");
        }
        //注销观察者和sd卡的挂载广播
        if (mLocalImagesObserver != null) {
            getContentResolver().unregisterContentObserver(mLocalImagesObserver);
            getContentResolver().unregisterContentObserver(mLocalVideosObserver);
            unregisterReceiver(mSDcardMountedReceiver);
        }
        super.onDestroy();
    }

先分析到这,接下在再补充。。。

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rom_Fisher

赠人玫瑰,手留余香。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值