直到我点击后退按钮 - 安卓才开启相机

时间:2016-10-28 17:15:44

标签: android onclicklistener

在我的Android应用程序中,当我首先点击按钮时它应该打开相机,一旦我捕获图像,它应该重定向到一个新的活动。

但是,当我点击按钮时,它会重定向到新活动,一旦我点击后退按钮,它就会打开相机。

我无法理解我的代码中的问题是什么,看起来状况良好。有什么帮助?

    public void onCameraButtonClicked()
    {

        camera_btn.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
                        makingDirectory(dir);

                        storePicture(dir);
                    }
                }
        );
    }

    public void makingDirectory(String dir)
    {
        File newdir = new File(dir);
        newdir.mkdirs();
    }

    public void storePicture(String dir)
    {
        boolean flag_storePicture = false;
        // Here, the counter will be incremented each time, and the
        // picture taken by camera will be stored as 1.jpg,2.jpg
        // and likewise.
        count++;
        String file = dir+count+".jpg";
        File newfile = new File(file);
        try
        {
            newfile.createNewFile();
            Uri outputFileUri = Uri.fromFile(newfile);

            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

            startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
            flag_storePicture = true;
            Log.d("myApp", "Hiiiiii from inside");
        }
        catch (IOException e)
        {

        }
        finally {
            Log.d("myApp", "Hiiiiii");
            Intent camera_intent = new Intent("com.example.lalinda.googlemap1.Camera");
            startActivity(camera_intent);
        }
    }

在我的logcat中我收到此消息。

Skipped 62 frames!  The application may be doing too much work on its main thread.

1 个答案:

答案 0 :(得分:2)

正如你所清楚的那样,问题是控制流程,

在try块中,已为您打开camera应用

 startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);

然后在finally执行后立即

finally {
            Log.d("myApp", "Hiiiiii");
            Intent camera_intent = new Intent("com.example.lalinda.googlemap1.Camera");
            startActivity(camera_intent);
        }

现在您的相机应用程序已经进行了googlemap1.Camera活动,因此如果按回来,您将找到相机应用程序。

解决方案:根据您的要求,将finally广告代码块移至onActivityResult以及if条件,以验证图片捕获任务是否完成。像

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK){ // image captured successfully 
            //..code to start your other activity 
        Intent camera_intent = new Intent("com.example.lalinda.googlemap1.Camera");
        startActivity(camera_intent);
        }else{
           // ..  image capture failure , user pressed cancel etc
           }
    }