Android + obsługa aparatu

0

Witam,

potrzebuje zrobić prostą appkę robiącą określoną (przez użytkownika) ilość fotek w określonych odstępach czasowych. Ale mam problem z samą obsługą aparatu.

Na developer.android.com jest tutorial jak to zrobić, ale wtedy aplikacja przełącza nas na gotową już aplikację aparatu, a mnie chodzi o to, aby nacisnąć przycisk np zrób zdjęcia i żeby zdjęcie pojawiło się w określonym przez nas katalogu. Nie musi być podglądu robienia zdjęć w aplikacji, ale może być (mały jakiś).

Oto co mam do tej pory:

camera.takePicture(null, null,
					        new PhotoHandler(getApplicationContext()));

Powyżej robię zdjęcie (oczywiście po wykryciu czy kamera istnieje, czy jest to kamera przednia itp)

package com.example.tester;

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

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

  private final Context context;

  public PhotoHandler(Context context) {
    this.context = context;
  }

  @Override
  public void onPictureTaken(byte[] data, Camera camera) {

    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

      Log.d(Constants.CONTENT_DIRECTORY, "Can't create directory to save image.");
      Toast.makeText(context, "Can't create directory to save image.",
          Toast.LENGTH_LONG).show();
      return;

    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
    String date = dateFormat.format(new Date());
    String photoFile = "Picture_" + date + ".jpg";

    String filename = pictureFileDir.getPath() + File.separator + photoFile;

    File pictureFile = new File(filename);

    try {
      FileOutputStream fos = new FileOutputStream(pictureFile);
      fos.write(data);
      fos.close();
      Toast.makeText(context, "New Image saved:" + photoFile,
          Toast.LENGTH_LONG).show();
    } catch (Exception error) {
      Log.d(Constants.CONTENT_DIRECTORY, "File" + filename + "not saved: "
          + error.getMessage());
      Toast.makeText(context, "Image could not be saved.",
          Toast.LENGTH_LONG).show();
    }
  }

  private File getDir() {
    File sdDir = Environment
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return new File(sdDir, "CameraAPIDemo");
  }
} 

Powyżej klasa PhotoHandler. Aplikacja działa, nic się nie wysypuje, testuję ją na fizycznym urządzeniu. Jednak nic się nie dzieje, a już na pewno nie robi zdjęć...

0

Kilka dni zabawy i dalej nie działa. Próbowałem kilku różnych tutoriali, dokumentacji technicznej, android sampla i dalej nic...

załączam obecny stan :

Klasa główna

public class Main extends Activity {
	private final static String DEBUG_TAG = "Main";
	private Camera camera;
	private int cameraId = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// do we have a camera?
		if (!getPackageManager()
				.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
					.show();
		} else {
			cameraId = findFrontFacingCamera();
			camera = Camera.open(cameraId);
			if (cameraId < 0) {
				Toast.makeText(this, "No front facing camera found.",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	public void onClick(View view) {
		camera.takePicture(null, null,
				new PhotoHandler(getApplicationContext()));
	}

	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) {
				Log.d(DEBUG_TAG, "Camera found");
				cameraId = i;
				break;
			}
		}
		return cameraId;
	}

	@Override
	protected void onPause() {
		if (camera != null) {
			camera.release();
			camera = null;
		}
		super.onPause();
	}

}

Klasa definiująca debug_tag użyty w photohandlerze


public class Constants {
	public final static String DEBUG_TAG = "com.example.camapi";

}

Klasa zarządzająca drugim layoutem



public class TextureViewActivity extends Activity implements
		TextureView.SurfaceTextureListener {
	private Camera camera;
	private TextureView mTextureView;
	private float rotation = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mTextureView = new TextureView(this);
		mTextureView.setSurfaceTextureListener(this);
		setContentView(mTextureView);

	}

	@Override
	public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
			int height) {
		camera = Camera.open(findFirstFrontFacingCamera());

		Camera.Size previewSize = camera.getParameters().getPreviewSize();
		mTextureView.setLayoutParams(new FrameLayout.LayoutParams(
				previewSize.width, previewSize.height, Gravity.CENTER));

		try {
			camera.setPreviewTexture(surface);
		} catch (IOException t) {
		}

		camera.startPreview();

		mTextureView.setAlpha(0.8f);
		mTextureView.setRotation(45.0f);

	}

	public void onClick(View view) {
		camera.takePicture(null, null,
				new PhotoHandler(getApplicationContext()));
	}

	private int findFirstFrontFacingCamera() {
		int cameraId = -1;
		// search for the first 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;
				break;
			}
		}
		return cameraId;
	}

	@Override
	public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width,
			int height) {
		// Ignored, the Camera does all the work for us
	}

	@Override
	public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
		camera.stopPreview();
		camera.release();
		return true;
	}

	@Override
	public void onSurfaceTextureUpdated(SurfaceTexture surface) {
		// Called whenever a new frame is available and displayed in the
		// TextureView
		rotation += 1.0f;
		if (rotation > 360) {
			rotation = 0;
		}
		mTextureView.setRotation(rotation);
	}
}

Pierwszy layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/cameraPreview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </FrameLayout>

    <Button
        android:id="@+id/captureFront"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Make Photo" 
        android:onClick="onClick"

        />

</RelativeLayout>

Drugi layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/captureFront"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="onClick"
        android:text="Start Rotation" />

    <TextureView
        android:id="@+id/textureView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

I photohandler


public class PhotoHandler implements PictureCallback {

	private final Context context;

	public PhotoHandler(Context context) {
		this.context = context;
	}

	@Override
	public void onPictureTaken(byte[] data, Camera camera) {

		File pictureFileDir = getDir();

		if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

			Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");
			Toast.makeText(context, "Can't create directory to save image.",
					Toast.LENGTH_LONG).show();
			return;

		}

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
		String date = dateFormat.format(new Date());
		String photoFile = "Picture_" + date + ".jpg";

		String filename = pictureFileDir.getPath() + File.separator + photoFile;

		File pictureFile = new File(filename);

		try {
			FileOutputStream fos = new FileOutputStream(pictureFile);
			fos.write(data);
			fos.close();
			Toast.makeText(context, "New Image saved:" + photoFile,
					Toast.LENGTH_LONG).show();
		} catch (Exception error) {
			Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "
					+ error.getMessage());
			Toast.makeText(context, "Image could not be saved.",
					Toast.LENGTH_LONG).show();
		}
	}

	private File getDir() {
		File sdDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		return new File(sdDir, "CameraAPIDemo");
	}
}

Efekt taki, że żadnych błędów, aplikacja włącza się na telefonie i można sobie w nieskończoność naciskać button "Make photo", co nie daje żadnych efektów.

Jest ktoś w stanie wskazać błąd?
Wersja androida się zgadza z manifestem, w manifeście dodane są android permissions dla CAMERA i WRITE EXTERNAL STORAGE

0

Jest jeden błąd, kamera powinna być BACK a nie FRONT, ale to dalej nie zmienia tego, że nie działa...

1 użytkowników online, w tym zalogowanych: 0, gości: 1