拍照后应用程序突然崩溃,旋转屏幕并return到activity

App suddenly crashes after taking a picture, rotate the screen and return to the activity

拍照后应用程序突然崩溃,旋转屏幕并return到activity。 我正在制作一个 Android 应用程序,它需要拍照并将其路线作为字符串存储到数据库中,我按照官方 google 教程 (https://developer.android.com/training/camera/photobasics#kotlin) 来执行此操作而无需实现我自己的相机应用程序。 但是当我执行以下步骤时遇到问题: • 使用媒体 dispatchTakePictureIntent() 打开包含拍照逻辑的 activity • 以人像模式启动相机。 • 将屏幕旋转到水平/相机旋转到横向模式。 • 拍照并点击“确定”按钮。 • 应用程序崩溃。

但是如果不旋转phone相机打开我可以随意使用拍摄照片。

我的代码是这样的:

   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(requestCode == CodigosDeSolicitud.ANADIR_FOTOGRAFIA && resultCode == Activity.RESULT_OK){
            setPic()
        }
    }

    @Throws(IOException::class)
    private fun createImageFile() : File{

        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir : File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
                "JPEG_${timeStamp}_",
                ".jpg",
                storageDir
        ).apply {
            mCurrentPhotoPath = absolutePath
        }

    }

    private fun dispatchTakePicktureIntent(){
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also {takePictureIntent ->
            takePictureIntent.resolveActivity(packageManager)?.also {
                val photoFile : File? = try{
                    createImageFile()
                } catch (ex : IOException){
                    null
                }
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                            this,
                            "com.kps.spart.android.fileprovider",
                            it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, CodigosDeSolicitud.ANADIR_FOTOGRAFIA)
                }
            }

        }
    }

    private fun setPic(){
        val targetW: Int = iconoUsuarioIV.width
        val targetH: Int = iconoUsuarioIV.height

        val bmOptions = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
            BitmapFactory.decodeFile(mCurrentPhotoPath,this)
            val photoW: Int = outWidth
            val photoH: Int = outHeight

            val scaleFactor : Int = Math.min(photoW / targetW, photoH / targetH)

            inJustDecodeBounds = false
            inSampleSize = scaleFactor
            inPurgeable = true
        }

        val exif = ExifInterface(mCurrentPhotoPath)
        val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_UNDEFINED)
        Toast.makeText(this@RegistrarUsuarioActivity,"Orientacion: " + orientation, Toast.LENGTH_SHORT).show()

        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions)?.also { bitmap ->
            iconoUsuarioIV.setImageBitmap(bitmap)
        }

我的 logcat 给出了下一个错误:

Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1000, result=-1, data=null} to activity {com.kps.spart.moskimedicationreminder/com.kps.spart.moskimedicationreminder.RegistrarUsuarioActivity}: java.lang.ArithmeticException: divide by zero
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4519)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3777)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3845) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3065) 
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4950) 
    at android.app.ActivityThread.-wrap19(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1730) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:7000) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 
 Caused by: java.lang.ArithmeticException: divide by zero
    at com.kps.spart.moskimedicationreminder.RegistrarUsuarioActivity.setPic(RegistrarUsuarioActivity.kt:223)
    at com.kps.spart.moskimedicationreminder.RegistrarUsuarioActivity.onActivityResult(RegistrarUsuarioActivity.kt:170)
    at android.app.Activity.dispatchActivityResult(Activity.java:7630)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4515)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3777) 
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3845) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3065) 
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4950) 
    at android.app.ActivityThread.-wrap19(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1730) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:7000) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 

使用中断点我发现当我在拍照时旋转屏幕时activity被破坏但是如果我不在那个activity为什么会发生这种情况我该如何解决这个问题?

我自己偶然发现了这个(遵循相同的指南)。我知道这个问题很老了,但我正在为可能遇到的任何其他问题发布解决方案。

问题出在被调用两次的 onCreate 方法中(当您 return 到 activity 拍照后,设备旋转后)。为了避免它,您应该阻止 dispatchTakePicktureIntent 的第二次调用(我猜您在 onCreate 方法中这样做)。

我是这样实现的:

class TakePhotoActivity : AppCompatActivity() {

    private val captureRequestCode = 1
    private val captureState = "capture_in_progress"
    private val capturePhotoPath = "capture_photo_path"
    private var photoPath: String? = null
    private var captureInProgress: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_take_photo)
        captureInProgress = savedInstanceState?.getBoolean(captureState) ?: false
        photoPath = savedInstanceState?.getString(capturePhotoPath)

        if(!captureInProgress){
            captureInProgress = true
            dispatchTakePictureIntent()
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putBoolean(captureState, captureInProgress)
        outState.putString(capturePhotoPath, photoPath)
        super.onSaveInstanceState(outState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == captureRequestCode && resultCode == RESULT_OK) {
            user_photo.adjustViewBounds = true
            val imgFile = File(photoPath ?: "")

            if (imgFile.exists()) {
                val myBitmap = BitmapFactory.decodeFile(imgFile.absolutePath)
                user_photo.setImageBitmap(myBitmap)
                runImageLabelingOnCurrentPicture(myBitmap)
            }
            captureInProgress = false
        }
    }
}

您需要将标志 'taking picture in process' 保存到 savedInstanceState 中,如果存在于 onCreate 方法中则将其恢复。就这些了。