java - 单击按钮触发camera.take拍照[工作]和通过函数调用触发camera.take拍照[不工作]之间的区别

标签 java android image camera

我被困在这个问题上。我的应用程序以编程方式单击多个图像。 问题是我的拍照调用位于按钮监听器单击功能内。 1.当我单击按钮时,它会触发有效的拍照线程。 2.如果我直接调用 obj.run() 它不会->显示运行时拍照失败。 3.如果我执行 btn.perform click - 仍然失败。

我正在构建一个应用程序,该应用程序监听套接字并在触发器上单击多个图像,然后将它们保存以创建 .gif。

code:


 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     //   android.support.v7.appcompat.R.layout.activity_main;
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        myContext = this;
        initialize();

    }

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                cameraFront = true;
                break;
            }
        }
        return cameraId;
    }

    private int findBackFacingCamera() {
        int cameraId = -1;
        //Search for the back facing camera
        //get the number of cameras
        int numberOfCameras = Camera.getNumberOfCameras();
        //for every camera check
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
                cameraId = i;
                cameraFront = false;
                break;
            }
        }
        return cameraId;
    }

    public  void onResume() {
        super.onResume();
        if (!hasCamera(myContext)) {
            Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
            toast.show();
            finish();
        }
        if (mCamera == null) {
            //if the front facing camera does not exist
            if (findFrontFacingCamera() < 0) {
                Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
                switchCamera.setVisibility(View.GONE);
            }
            mCamera = Camera.open(findFrontFacingCamera());
           // mCamera.Parameters.class.
            mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
            capture.performClick();
            Log.d("naval", "onresume- clicked performed");

        }
    }

    public void initialize() {
        cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
        mPreview = new CameraPreview(myContext, mCamera);
        cameraPreview.addView(mPreview);

        capture = (Button) findViewById(R.id.button_capture);
       // capture.setVisibility(View.GONE);
        capture.setOnClickListener(captrureListener);
       // capture.performClick();

        switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
        switchCamera.setVisibility(View.GONE); // JUST CHANGE THIS TO MAKE SWITCH CAMERA WORKS
        switchCamera.setOnClickListener(switchCameraListener);
        Log.d("naval", "initialize");


    }

    OnClickListener switchCameraListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            //get the number of cameras
            int camerasNumber = Camera.getNumberOfCameras();
            if (camerasNumber > 1) {
                //release the old camera instance
                //switch camera, from the front and the back and vice versa

                releaseCamera();
                chooseCamera();
            } else {
                Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    };

    public void chooseCamera() {
        //if the camera preview is the front
      if (cameraFront) {
            int cameraId = findBackFacingCamera();
           if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = Camera.open(cameraId);
                mPicture = getPictureCallback();
                mPreview.refreshCamera(mCamera);
           }
       } else {
            int cameraId = findFrontFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = Camera.open(cameraId);
                mPicture = getPictureCallback();
                mPreview.refreshCamera(mCamera);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //when on Pause, release camera in order to be used from other applications
        releaseCamera();
        Log.d("naval", "onpause");

    }

    private boolean hasCamera(Context context) {
        //check if the device has camera
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    private PictureCallback getPictureCallback() {
        PictureCallback picture = new PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                //make a new picture file
                File pictureFile = getOutputMediaFile();
                Log.d("naval", "picture call back start");

                if (pictureFile == null) {
                    return;
                }
                try {
                    //write the file
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    Log.d("naval", "picture call back stream creation");
                    fos.write(data);
                    fos.close();
                    Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
                    Log.d("naval", "picture call back toast");
                    toast.show();

                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }

                //refresh camera to continue preview
                mPreview.refreshCamera(mCamera);
                //cameraPreview.start();

            }
        };
        return picture;
    }

    OnClickListener captrureListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Thread.sleep(1000);
            }catch (Exception e)
            {
                e.printStackTrace();
            }
            CaptureThread captureThread = new CaptureThread();
            captureThread.start();

       /*     String str = "";


            while(true)
             {
                 Log.d("naval","waiting for start inside file loop");
                 str = readFromFile();

                 if(str.equals("start")) {
                      Log.d("naval","calling capture object");
                      str = "";
                      CaptureThread captureThread = new CaptureThread();
                      captureThread.start();
                  }
                 else
                  {
                      try {
                          Log.d("naval","sleeping inside str loop");
                          Thread.sleep(1000);
                      }catch(Exception e)
                      {
                          e.printStackTrace();
                      }
                      continue;
                      // put sleep here
                  }

                 // read text file here at location /sdcard/info/info.txt

             }*/
        }
    };

    private String readFromFile() {

        String ret = "";

        try {
            FileInputStream fis = new FileInputStream (new File("/storage/emulated/0/info/info.txt"));  // 2nd line

           // InputStream inputStream = openFileInput("/storage/emulated/0/info/info.txt");

            if ( fis != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(fis);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }

                fis.close();
                ret = stringBuilder.toString();
                Log.d("naval- string",ret);
                if(!ret.isEmpty())
                {
                    Log.d("naval","str is not null");
                    //delete file or clear file and create one
                    File fil = new File("/storage/emulated/0/info/info.txt");
                    fil.delete();

                    // create
                    File file = new File("/storage/emulated/0/info/info.txt");
                    file.createNewFile();


                }
            }
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }

        return ret;
    }
    //make picture and save to a folder
    private static File getOutputMediaFile() {
        //make a new file directory inside the "sdcard" folder
        File mediaStorageDir = new File("/sdcard/", "pics");
        Log.d("naval", "save picture function");

        //if this "JCGCamera folder does not exist
        if (!mediaStorageDir.exists()) {
            //if you cannot make this folder return
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        Log.d("naval", "cave picture betweent");
        //take the current timeStamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        //and make a media file:
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "pic" + glo + ".png");
        Log.d("naval", "File path above");
        glo++;

        return mediaFile;
    }

    private void releaseCamera() {
        // stop and release camera
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }



    class CaptureThread extends Thread {

        @Override
        public void run() {

           int count = 0;

                        while(count < 6) {

                            **mCamera.takePicture(null, null, mPicture);**

                            count++;

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException exception) {
                                exception.printStackTrace();
                            }
                        }
                        createGif();

        }


public void createGif()
{

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    AnimatedGifEncoder encoder = new AnimatedGifEncoder();
    BitmapFactory.Options options=new BitmapFactory.Options();

    options.inSampleSize = 6;

    encoder.setDelay(100);
    encoder.start(bos);
    for(int i = 0;i<6;i++){
        Bitmap bMap = BitmapFactory.decodeFile("/storage/emulated/0/pics/pic"+i+".png",options);
        Log.d("naval","added image");
        encoder.addFrame(bMap);
    }
    encoder.finish();

    writeToFile(bos.toByteArray());
}

        public void writeToFile(byte[] array) {
            try {
                String path = Environment.getExternalStorageDirectory() + "/gif/gif.gif";
                FileOutputStream stream = new FileOutputStream(path);
                stream.write(array);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

最佳答案

好吧,答案是来自按钮单击,它来自 UI 线程。但函数调用却没有。要运行此函数,请从 UI 线程调用该函数。它会起作用的!!

关于java - 单击按钮触发camera.take拍照[工作]和通过函数调用触发camera.take拍照[不工作]之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067086/

相关文章:

导出为 jar 后,Java 找不到文件

java - 是什么导致 JVM 退出代码 10?

java - 在java单例中获取内部类的实例

android - 如何混合 android.support.v4.app.Fragment 和 android.app.Fragment

java - 如何将 PNG 文件数组添加到 ArrayList<Image> - Java

java - Apache PDFBox - 无法读取 PDF 中的所有字段

android - 有没有一种方法可以用 Robolectric 测试拾取器?

android - 为 child 设置默认重力

image - Blogger 新 Notable 主题 : thumbnail image box 的问题

C++ - 比较两张 .jpeg/.png 图片并将不同的像素打印到矩阵中