1

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

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

我的代码是这样的:

   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) 

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

4

1 回答 1

2

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

问题出在onCreate被调用两次的方法中(当您在拍照后返回活动时,在设备旋转后)。为了避免它,你应该阻止第二次调用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
        }
    }
}

如果方法中存在“正在拍照”标志,则需要将其保存savedInstanceState并恢复onCreate。就这些。

于 2020-01-20T17:43:50.543 回答