2016-02-08 2 views
-1

Я хочу построить приложение андроида о камере два просмотра с одной камеры enter image description hereAndroid камеры два предварительного просмотра с одной камеры

Я попытался построить приложение, я с помощью SurfaceView в Android Studio, но у меня есть проблема, enter image description here

Я хочу пример кода, Можете ли вы мне помочь? Большое вам спасибо.


Я попробовал приложение.

AndroidSurfaceviewExample.java

package th.in.cybernoi.cardboardview; 
 

 
import java.io.File; 
 
import java.io.FileNotFoundException; 
 
import java.io.FileOutputStream; 
 
import java.io.IOException; 
 
import java.text.SimpleDateFormat; 
 
import java.util.Date; 
 

 
import android.app.Activity; 
 
import android.content.Context; 
 
import android.content.pm.PackageManager; 
 
import android.hardware.Camera; 
 
import android.hardware.Camera.PictureCallback; 
 
import android.hardware.Camera.CameraInfo; 
 
import android.hardware.Camera.ShutterCallback; 
 
import android.os.Bundle; 
 
import android.util.Log; 
 
import android.view.SurfaceHolder; 
 
import android.view.SurfaceView; 
 
import android.view.View; 
 
import android.view.WindowManager; 
 
import android.view.View.OnClickListener; 
 
import android.widget.Button; 
 
import android.widget.LinearLayout; 
 
import android.widget.TextView; 
 
import android.widget.Toast; 
 

 

 
public class AndroidSurfaceviewExample extends Activity implements SurfaceHolder.Callback { 
 
    TextView testView; 
 

 
    Camera camera; 
 
    SurfaceView surfaceView; 
 
    SurfaceHolder surfaceHolder; 
 

 
    PictureCallback rawCallback; 
 
    ShutterCallback shutterCallback; 
 
    PictureCallback jpegCallback; 
 

 

 
    /** Called when the activity is first created. */ 
 
    @Override 
 
    public void onCreate(Bundle savedInstanceState) { 
 
     super.onCreate(savedInstanceState); 
 

 
     setContentView(R.layout.activity_main); 
 

 
     surfaceView = (SurfaceView) findViewById(R.id.surfaceView); 
 
     surfaceHolder = surfaceView.getHolder(); 
 

 
     // Install a SurfaceHolder.Callback so we get notified when the 
 
     // underlying surface is created and destroyed. 
 
     surfaceHolder.addCallback(this); 
 

 
     // deprecated setting, but required on Android versions prior to 3.0 
 
     surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
 

 
     jpegCallback = new PictureCallback() { 
 
      public void onPictureTaken(byte[] data, Camera camera) { 
 
       FileOutputStream outStream = null; 
 
       try { 
 
        outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis())); 
 
        outStream.write(data); 
 
        outStream.close(); 
 
        Log.d("Log", "onPictureTaken - wrote bytes: " + data.length); 
 
       } catch (FileNotFoundException e) { 
 
        e.printStackTrace(); 
 
       } catch (IOException e) { 
 
        e.printStackTrace(); 
 
       } finally { 
 
       } 
 
       Toast.makeText(getApplicationContext(), "Picture Saved", 2000).show(); 
 
       refreshCamera(); 
 
      } 
 
     }; 
 
    } 
 

 

 

 
    //Surfacrview 
 
    public void captureImage(View v) throws IOException { 
 
     //take the picture 
 
     camera.takePicture(null, null, jpegCallback); 
 
    } 
 

 
    public void refreshCamera() { 
 
     if (surfaceHolder.getSurface() == null) { 
 
      // preview surface does not exist 
 
      return; 
 
     } 
 

 
     // stop preview before making changes 
 
     try { 
 
      camera.stopPreview(); 
 
     } catch (Exception e) { 
 
      // ignore: tried to stop a non-existent preview 
 
     } 
 

 
     // set preview size and make any resize, rotate or 
 
     // reformatting changes here 
 
     // start preview with new settings 
 
     try { 
 
      camera.setPreviewDisplay(surfaceHolder); 
 
      camera.startPreview(); 
 
     } catch (Exception e) { 
 

 
     } 
 
    } 
 

 
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
 
     // Now that the size is known, set up the camera parameters and begin 
 
     // the preview. 
 
     refreshCamera(); 
 
    } 
 

 
    public void surfaceCreated(SurfaceHolder holder) { 
 
     try { 
 
      // open the camera 
 
      camera = Camera.open(); 
 
     } catch (RuntimeException e) { 
 
      // check for exceptions 
 
      System.err.println(e); 
 
      return; 
 
     } 
 
     Camera.Parameters param; 
 
     param = camera.getParameters(); 
 

 
     // modify parameter 
 
     param.setPreviewSize(352, 288); 
 
     camera.setParameters(param); 
 
     try { 
 
      // The Surface has been created, now tell the camera where to draw 
 
      // the preview. 
 
      camera.setPreviewDisplay(surfaceHolder); 
 
      camera.startPreview(); 
 
     } catch (Exception e) { 
 
      // check for exceptions 
 
      System.err.println(e); 
 
      return; 
 
     } 
 
    } 
 

 
    public void surfaceDestroyed(SurfaceHolder holder) { 
 
     // stop preview and release camera 
 
     camera.stopPreview(); 
 
     camera.release(); 
 
     camera = null; 
 
    } 
 

 
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    xmlns:tools="http://schemas.android.com/tools" 
 
    android:layout_width="match_parent" 
 
    android:layout_height="match_parent" 
 
    android:orientation="horizontal" 
 
    tools:context="th.in.cybernoi.cardboardview.MainActivity"> 
 

 
    <SurfaceView 
 
     android:id="@+id/surfaceView" 
 
     android:layout_width="0dp" 
 
     android:layout_height="match_parent" 
 
     android:layout_weight="1" /> 
 

 
    <SurfaceView 
 
     android:id="@+id/surfaceView" 
 
     android:layout_width="0dp" 
 
     android:layout_height="match_parent" 
 
     android:layout_weight="1" /> 
 

 
</LinearLayout>


Update Изменить код Сейчас: 9/02/16

  1. редактировать в AndroidSurfaceviewExample.java
    • добавить публичный недействительным onPreviewFrame()

public class AndroidSurfaceviewExample extends Activity implements SurfaceHolder.Callback { 
 
    TextView testView; 
 

 
    Camera camera; 
 
    SurfaceHolder camera01; 
 
    SurfaceHolder camera02; 
 

 
    SurfaceView surfaceViewLeft; 
 
    SurfaceHolder surfaceHolderLeft; 
 

 
    SurfaceView surfaceViewRight; 
 
    SurfaceHolder surfaceHolderRight; 
 

 
    PictureCallback rawCallback; 
 
    ShutterCallback shutterCallback; 
 
    PictureCallback jpegCallback; 
 
    /** 
 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
 
    */ 
 
    private GoogleApiClient client; 
 

 

 
    /** 
 
    * Called when the activity is first created. 
 
    */ 
 
    @Override 
 
    public void onCreate(Bundle savedInstanceState) { 
 
     super.onCreate(savedInstanceState); 
 

 
     setContentView(R.layout.activity_main); 
 

 
     surfaceViewLeft = (SurfaceView) findViewById(R.id.surfaceViewLeft); 
 
     surfaceHolderLeft = surfaceViewLeft.getHolder(); 
 

 
     surfaceViewRight = (SurfaceView) findViewById(R.id.surfaceViewRight); 
 
     surfaceHolderRight = surfaceViewRight.getHolder(); 
 

 
     // Install a SurfaceHolder.Callback so we get notified when the 
 
     // underlying surface is created and destroyed. 
 
     surfaceHolderLeft.addCallback(this); 
 
     surfaceHolderRight.addCallback(this); 
 

 
     // deprecated setting, but required on Android versions prior to 3.0 
 
     surfaceHolderLeft.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
 
     surfaceHolderRight.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
 

 
     /* 
 
     jpegCallback = new PictureCallback() { 
 
      public void onPictureTaken(byte[] data, Camera camera) { 
 
       FileOutputStream outStream = null; 
 
       try { 
 
        outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis())); 
 
        outStream.write(data); 
 
        outStream.close(); 
 
        Log.d("Log", "onPictureTaken - wrote bytes: " + data.length); 
 
       } catch (FileNotFoundException e) { 
 
        e.printStackTrace(); 
 
       } catch (IOException e) { 
 
        e.printStackTrace(); 
 
       } finally { 
 
       } 
 
       Toast.makeText(getApplicationContext(), "Picture Saved", 2000).show(); 
 
       refreshCamera(); 
 
      } 
 

 

 
     }; 
 
     */ 
 
     // ATTENTION: This was auto-generated to implement the App Indexing API. 
 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
 
     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
 
    } 
 

 

 
    //Surfacrview 
 

 

 
    public void refreshCamera() { 
 
     if (surfaceHolderLeft.getSurface() == null) { 
 
      // preview surface does not exist 
 
      return; 
 
     } 
 

 
     // stop preview before making changes 
 
     try { 
 
      camera.stopPreview(); 
 
     } catch (Exception e) { 
 
      // ignore: tried to stop a non-existent preview 
 
     } 
 

 
     // set preview size and make any resize, rotate or 
 
     // reformatting changes here 
 
     // start preview with new settings 
 
     try { 
 
      camera.setPreviewDisplay(surfaceHolderLeft); 
 
      camera.startPreview(); 
 

 

 
     } catch (Exception e) { 
 

 
     } 
 
    } 
 

 

 

 
    public void onPreviewFrame() { 
 

 
     if (surfaceHolderRight.getSurface() == null) { 
 
      // preview surface does not exist 
 
      return; 
 
     } 
 

 

 
     // stop preview before making changes 
 
     try { 
 
      camera.stopPreview(); 
 
     } catch (Exception e) { 
 
      // ignore: tried to stop a non-existent preview 
 
     } 
 

 
     // set preview size and make any resize, rotate or 
 
     // reformatting changes here 
 
     // start preview with new settings 
 
     try { 
 
      surfaceHolderLeft.lockCanvas(); 
 
      camera.setPreviewDisplay(surfaceHolderRight); 
 
      camera.setPreviewCallback((Camera.PreviewCallback) surfaceHolderLeft); 
 
      camera.startPreview(); 
 

 

 
     } catch (Exception e) { 
 

 
     } 
 

 

 
    } 
 

 

 
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
 
     // Now that the size is known, set up the camera parameters and begin 
 
     // the preview. 
 
     refreshCamera(); 
 
     onPreviewFrame(); 
 
     
 
    } 
 

 
    public void surfaceCreated(SurfaceHolder holder) { 
 
     try { 
 
      // open the camera 
 
      camera = Camera.open(); 
 
     } catch (RuntimeException e) { 
 
      // check for exceptions 
 
      System.err.println(e); 
 
      return; 
 
     } 
 
     Camera.Parameters param; 
 
     param = camera.getParameters(); 
 

 
     // modify parameter 
 
     param.setPreviewSize(352, 288); 
 
     camera.setParameters(param); 
 
     try { 
 
      // The Surface has been created, now tell the camera where to draw 
 
      // the preview. 
 
      camera.setPreviewDisplay(surfaceHolderLeft); 
 
      camera.startPreview(); 
 
     } catch (Exception e) { 
 
      // check for exceptions 
 
      System.err.println(e); 
 
      return; 
 
     } 
 
    } 
 

 
    public void surfaceDestroyed(SurfaceHolder holder) { 
 
     // stop preview and release camera 
 
     camera.stopPreview(); 
 
     camera.release(); 
 
     camera = null; 
 
    } 
 

 
    @Override 
 
    public void onStart() { 
 
     super.onStart(); 
 

 
     // ATTENTION: This was auto-generated to implement the App Indexing API. 
 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
 
     client.connect(); 
 
     Action viewAction = Action.newAction(
 
       Action.TYPE_VIEW, // TODO: choose an action type. 
 
       "AndroidSurfaceviewExample Page", // TODO: Define a title for the content shown. 
 
       // TODO: If you have web page content that matches this app activity's content, 
 
       // make sure this auto-generated web page URL is correct. 
 
       // Otherwise, set the URL to null. 
 
       Uri.parse("http://host/path"), 
 
       // TODO: Make sure this auto-generated app deep link URI is correct. 
 
       Uri.parse("android-app://th.in.cybernoi.cardboardview/http/host/path") 
 
     ); 
 
     AppIndex.AppIndexApi.start(client, viewAction); 
 
    } 
 

 
    @Override 
 
    public void onStop() { 
 
     super.onStop(); 
 

 
     // ATTENTION: This was auto-generated to implement the App Indexing API. 
 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
 
     Action viewAction = Action.newAction(
 
       Action.TYPE_VIEW, // TODO: choose an action type. 
 
       "AndroidSurfaceviewExample Page", // TODO: Define a title for the content shown. 
 
       // TODO: If you have web page content that matches this app activity's content, 
 
       // make sure this auto-generated web page URL is correct. 
 
       // Otherwise, set the URL to null. 
 
       Uri.parse("http://host/path"), 
 
       // TODO: Make sure this auto-generated app deep link URI is correct. 
 
       Uri.parse("android-app://th.in.cybernoi.cardboardview/http/host/path") 
 
     ); 
 
     AppIndex.AppIndexApi.end(client, viewAction); 
 
     client.disconnect(); 
 
    } 
 
}

+0

проверить эту ссылку http://examples.javacodegeeks.com/android/core/hardware/camera-hardware/android-camera-example/ – Stallion

+0

Спасибо за помощь мне:), я пробовал, но не знаю около второго вида в одной камере. Не могли бы вы мне помочь. –

+0

Какова, собственно, проблема, с которой вы сталкиваетесь? Вы говорите «не удалось», но что это значит? происходит ли сбой вашей программы? Работает ли один образ, а другой нет? Предполагается ли, что второе представление будет каким-то иным, чем первое, или это просто дублирующее изображение на одном экране? – rothloup

ответ

0

Каждый элемент в потребности макета иметь уникальный идентификатор. вы определили оба элемента экрана как @+id/surfaceView. Попробуйте сделать их уникальными. См. Измененный файл макета ниже - также не забудьте обновить исходный код, чтобы заполнить оба элемента экрана.

<?xml version="1.0" encoding="utf-8"?> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    xmlns:tools="http://schemas.android.com/tools" 
 
    android:layout_width="match_parent" 
 
    android:layout_height="match_parent" 
 
    android:orientation="horizontal" 
 
    tools:context="th.in.cybernoi.cardboardview.MainActivity"> 
 

 
    <SurfaceView 
 
     android:id="@+id/surfaceViewLeft" 
 
     android:layout_width="0dp" 
 
     android:layout_height="match_parent" 
 
     android:layout_weight="1" /> 
 

 
    <SurfaceView 
 
     android:id="@+id/surfaceViewRight" 
 
     android:layout_width="0dp" 
 
     android:layout_height="match_parent" 
 
     android:layout_weight="1" /> 
 

 
</LinearLayout>

Добавьте код в вашей программе ссылаться как объекты SurfaceView. Вы просто дублируете код, который у вас уже есть. Вы также должны проверить остальную часть своей программы на наличие других ссылок на объект SurfaceView, который необходимо обновить.

  surfaceViewLeft = (SurfaceView) findViewById(R.id.surfaceViewLeft); 
     surfaceHolderLeft = surfaceViewLeft.getHolder(); 

     // Install a SurfaceHolder.Callback so we get notified when the 
     // underlying surface is created and destroyed. 
     surfaceHolderLeft.addCallback(this); 

     // deprecated setting, but required on Android versions prior to 3.0 
     surfaceHolderLeft.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

     surfaceViewRight = (SurfaceView) findViewById(R.id.surfaceViewRight); 
     surfaceHolderRight = surfaceViewRight.getHolder(); 

     // Install a SurfaceHolder.Callback so we get notified when the 
     // underlying surface is created and destroyed. 
     surfaceHolderRight.addCallback(this); 

     // deprecated setting, but required on Android versions prior to 3.0 
     surfaceHolderRight.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

Ключа должен понимать, что, хотя левые и правые виды имеют одинаковый тип объекта (они оба SurfaceViews) они совершенно не знают друг о друге. Если вы хотите, чтобы что-то случилось с одним видом, вы должны написать код, который явно работает в этом представлении. Если вы также хотите, чтобы это произошло в другом представлении, вы должны написать код, который явно работает на другом представлении. Это пример наличия двух экземпляров того же объекта .

ОБНОВЛЕНИЕ: При дальнейшем выкапывании я вижу, что указанные изменения необходимы, но не достаточны.ваш вызов в camera.setPreviewDisplay(surfaceHolderLeft); позволяет определить только один предварительный просмотр SurfaceView, поэтому вы не можете просматривать его на двух поверхностях с помощью этого метода.

Чтобы выполнить то, что вы пытаетесь сделать, я рекомендую создать растровое изображение предварительного просмотра изображения (которое может быть получено в функции обратного вызова называется onPreviewFrame(), который похож на ваш onPictureTaken() callback. The bitmap data will be passed in through the first parameter) Then get a Canvas for each Surface view (by calling SurfaceHolder.lockCanvas() , and then draw the bitmap you saved onto each Canvas by calling Canvas.drawBitmap() `.Это должно нарисовать исходное изображение на каждом виде поверхности.

Поскольку вы будете рисовать на каждый экран surfaceView напрямую, вам следует избавиться от линии, которая устанавливает один из поверхностных представлений в качестве предварительного просмотра, чтобы вы конкурировали с камерой для доступа к розыгрышу там. Избавьтесь от линии camera.setPreviewDisplay(surfaceHolderLeft); и вместо этого напишите camera.setPreviewCallback(yourcallbackgoeshere);

Удачи.

+0

Большое вам спасибо, я пробовал исправить эту форму, рекомендую вас. - Я изменил serfaceViewLeft форму serfaceView. - я изменил поверхностьHolderLeft форма поверхностьHolder. - Я добавляю serfaceViewRight и surfaceHolderRight. - Исправляю файл .xml. Но «surfaceViewRight» не работает !. Вы можете мне помочь? Большое вам спасибо, сэр. –

+0

напишите свой новый код. Я не могу обновить весь проект для вас. – rothloup

+0

Okey, я обновляю код в сообщении. –

Смежные вопросы