I have written a code that used to display camera. Following is my layout file's code,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+id/previewLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
<LinearLayout
android:id="#+id/startBar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#drawable/leftbarbg"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="#+id/MuteBtn"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="2"
android:src="#drawable/mutebtn" />
<ImageView
android:id="#+id/VideosBtn"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="2"
android:src="#drawable/videosbtn" />
<ImageView
android:id="#+id/RecBtn"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="3"
android:src="#drawable/action_rec_selected" />
<ImageView
android:id="#+id/SettingsBtn"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="2"
android:src="#drawable/settingsbtn" />
<ImageView
android:id="#+id/ChatBtn"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="2"
android:src="#drawable/chatbtn" >
</ImageView>
</LinearLayout>
<RelativeLayout
android:id="#+id/stopBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="3dp"
android:visibility="gone" >
<ImageView
android:id="#+id/StopBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/stopbtn" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="70dp"
android:layout_marginTop="20dp" >
<ImageView
android:id="#+id/MenuBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/menubtn" />
<ImageView
android:id="#+id/LiveModeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:src="#drawable/livemodeoff" />
<Chronometer
android:id="#+id/video_chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textSize="28sp"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
And this is my code of CameraSurfaceview,
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
private MediaRecorder mediaRecorder;
private Boolean previewing;
private AutoFocusManager autoFocusManager;
private CameraDetectionObserver cameraDetectionObserver;
public CameraSurfaceView(Context context, AutoFocusManager autoFocusManager, CameraDetectionObserver cameraDetectionObserver) {
super(context);
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.autoFocusManager= autoFocusManager;
this.cameraDetectionObserver= cameraDetectionObserver;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (camera != null) {
Camera.Parameters parameters = camera.getParameters();
List< String > FlashModes = parameters.getSupportedFlashModes();
if (FlashModes.contains(Parameters.FLASH_MODE_AUTO)) {
parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
System.out.println("FLASH_MODE_AUTO");
}
List< String > WhiteBalance = parameters.getSupportedWhiteBalance();
if (WhiteBalance.contains(Parameters.WHITE_BALANCE_AUTO)) {
parameters.setFlashMode(Parameters.WHITE_BALANCE_AUTO);
System.out.println("WHITE_BALANCE_AUTO");
}
List< String > Antibanding = parameters.getSupportedAntibanding();
if (Antibanding.contains(Parameters.ANTIBANDING_AUTO)) {
parameters.setAntibanding(Camera.Parameters.ANTIBANDING_AUTO);
System.out.println("ANTIBANDING_AUTO");
}
List<Size> previews = parameters.getSupportedPreviewSizes();
int i = 0;
parameters.setPreviewSize( previews.get(4).width, previews.get(4).height );
camera.setParameters(parameters);
camera.startPreview();
autoFocusManager.startAutoFocus(camera);
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (camera != null) {
camera.release();
camera = null;
}
try {
camera = Camera.open(findBackFacingCamera());
camera.setPreviewDisplay(holder);
previewing = true;
cameraDetectionObserver.cameraInitializationStatus(true);
} catch (IOException e) {
camera.release();
camera = null;
}catch (Exception e) {
e.printStackTrace();
cameraDetectionObserver.cameraInitializationStatus(false);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (previewing) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
autoFocusManager.stopAutoFocus();
System.out.println("surface destroyed");
}
}
public void stopPreview(){
if (previewing) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
autoFocusManager.stopAutoFocus();
System.out.println("surface destroyed");
}
}
public Camera getCamera()
{
return this.camera;
}
public MediaRecorder getMediaRecorder(){
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mediaRecorder.setPreviewDisplay(holder.getSurface());
mediaRecorder.setVideoFrameRate(29);
mediaRecorder.setVideoSize(ByteArraysForLogin.VideoDimention.vWidth,ByteArraysForLogin.VideoDimention.vHeight);
return mediaRecorder;
}
private int findBackFacingCamera() {
int cameraId = -1;
// Search for the back 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_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
}
Above code works fine but it shows camera preview in stretched format in both landscape & portrait mode as following image.
However the resultan camera image is not stretched it is in normal mode only preview is stretched.
P.S. I am asking this question after trying this
try adding
getWindow().setFormat(PixelFormat.UNKNOWN);
in your onCreate
if that doesn't help maybe setting the rotation will?
camera.setDisplayOrientation(90);
and if that still doesn't help, all the results on Google are saying the aspect ratio of the SurfaceView must match the aspect ratio of the camera
try and use different resolution and increase frame width and height
Related
i made barcode scaner with barcodereader. Flash active on the layout can be used well...
But with button onclick, I do not understand using it ...
is there anything that can help ??
Layout Scanner :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.material.components.activity.ScanLogin">
<fragment
android:id="#+id/barcode_scanner"
android:name="info.androidhive.barcode.BarcodeReader"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:auto_focus="true"
app:use_flash="false" />
<info.androidhive.barcode.ScannerOverlay
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="-100dp"
android:background="#drawable/bg_red"
app:line_color="#color/global_color_green_primary"
app:line_speed="6"
app:line_width="4"
app:square_height="200"
app:square_width="200" />
<ImageButton
android:id="#+id/btnSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/barcode_scanner"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:background="#null"
android:contentDescription="#null"
android:src="#drawable/btn_off" />
</RelativeLayout>
Activity Scanner :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_scan);
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_scanner);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
toggleButtonImage();
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
ledoff();
} else {
ledon();
}
}
});
}
void ledon() {
isFlashOn = true;
playSound();
toggleButtonImage();
framescan.setTag(Camera.Parameters.FLASH_MODE_ON);
}
void ledoff() {
isFlashOn = false;
playSound();
toggleButtonImage();
framescan.setTag(Camera.Parameters.FLASH_MODE_OFF);
}
toglebutton serves to change the condition of the button to be on/off.
playsound works to play sound ... no problem with toglebutton and playsound. promlem in function use_flash.
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (Exception e) {
}
}}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}}
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}}
This code will help to achieve your requirements.And not forget to ask for the permission for the camera.
I wrote a class for camera preview
public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
private Camera camera;
public CameraView(Context context) {
super(context);
getHolder().addCallback(this);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public static void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera){
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation){
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
}else{
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
setCameraDisplayOrientation((Activity)getContext(), Camera.CameraInfo.CAMERA_FACING_BACK, camera);
Camera.Parameters parameters = camera.getParameters();
Camera.Size bestSize = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()){
if (size.width <= i1 && size.height <=i2) {
if (bestSize == null) {
bestSize = size;
} else {
int bestArea = bestSize.width * bestSize.height;
int newArea = size.width * size.height;
if (newArea > bestArea){
bestSize = size;
}
}
}
}
parameters.setPictureSize(bestSize.width, bestSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
try{
camera.setPreviewDisplay(surfaceHolder);
}catch (IOException e){
e.printStackTrace();
}
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
camera = null;
}
}
And then I wrote a layout file and I want to display the preview in the "SurfaceView"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camera_view" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentBottom="true"
android:weightSum="1">
<Button
android:id="#+id/stop_navigation"
android:layout_weight="0.5"
android:layout_height="32dp"
android:layout_width="0dp"
android:text="#string/stop_navigation"
android:textColor="#color/colorWhite"
android:textSize="12sp"
android:background="#color/colorAccent" />
</LinearLayout>
</RelativeLayout>
So how should I do in the main activity? Before I just did the below code and everything is fine.
CameraView cameraView = new CameraView(this);
addContentView(cameraView, new ActionBar.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT));
But now I need to put the preview into the layout I design.
Use FrameLayout and add CameraPreview to it.
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.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 {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
try this:
You need to Change in your SurfaceView in XML File.
Replace your surfaceView with this
<CameraView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camera_view" />
and your remaining code is Right.let me know after change
Hope this will helps...(:
At first you should add the camera permission in you Manifest.xml :
android:name="android.permission.CAMERA
And, add this in your activity :
#Override
protected void onResume() {
super.onResume();
mCameraView.start();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
Check this link, it's the easiest way to do it :
https://github.com/google/cameraview
I have some frames in my SD card.
There is list of frames in my activity.
Now when user click on frame, Camera preview will be displayed through that frame.
Please see image.
How can I archive this functionality ?
I searched about this but didn't get proper example.
You have to create your own Preview by extending the SurfaceView class.
Take FrameLayout with SurfaceView as child.and customise as per your needs
You can use SurfaceView and create a CustomView that will open the camera and you can adjust its size in the xml accordingly.
Create a class that extends SurfaceView and open camera inside that
CustomPreview.java
public class CustomPreview extends SurfaceView implements SurfaceHolder.Callback{
public static Bitmap mBitmap;
SurfaceHolder holder;
static Camera mCamera;
public CustomPreview(Context context, AttributeSet attrs) {
super(context, attrs);
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.getSupportedPreviewSizes();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera = Camera.open();
mCamera.setPreviewDisplay(holder);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
/***
*
* Take a picture and and convert it from bytes[] to Bitmap.
*
*/
public static void takeAPicture(){
Camera.PictureCallback mPictureCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
BitmapFactory.Options options = new BitmapFactory.Options();
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
}
};
mCamera.takePicture(null, null, mPictureCallback);
}
}
Now you can add this custom view in your XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/mySurfaceView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.mjl.CustomPreview
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</com.mjl.CustomPreview>
</FrameLayout>
<LinearLayout
android:layout_below="#id/mySurfaceView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center">
<ImageView android:id="#+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon"/>
</LinearLayout>
</RelativeLayout>
Now Enjoy the output.
I am trying to make a simple 2D Android game. In this, game I'm trying to make some buttons to control the character, while the character is shown in a SurfaceView. Currently, the SurfaceView is rendering only a black screen.
This is my MainActivity, which extends Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
GameView gm = (GameView)findViewById(R.id.snake_surface);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.main, menu);
return true;
}
The GameView class, which extends SurfaceView:
private HeroSprite hero;
public GameView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
gameLoopThread = new GameLoopThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
createHero();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,int width, int height) {
}
});
bmpBlood = BitmapFactory.decodeResource(context.getResources(), R.drawable.blood1);
}
private void createHero(){
hero=(createHeroSprite(R.drawable.aslan));
}
private HeroSprite createHeroSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new HeroSprite(this, bmp);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.tavsan));
sprites.add(createSprite(R.drawable.fare));
sprites.add(createSprite(R.drawable.sansar));
sprites.add(createSprite(R.drawable.tavsan));
sprites.add(createSprite(R.drawable.fare));
sprites.add(createSprite(R.drawable.sansar));
sprites.add(createSprite(R.drawable.tavsan));
sprites.add(createSprite(R.drawable.fare));
sprites.add(createSprite(R.drawable.sansar));
sprites.add(createSprite(R.drawable.tavsan));
sprites.add(createSprite(R.drawable.tavsan));
}
private Sprite createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GREEN);
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
hero.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if ((sprite).isCollition(x, y)) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
break;
}
}
}
}
return true;
}
My GameLoopThread class, which extends Thread
static final long FPS = 10;
private GameView view;
private boolean running = false;
public GameLoopThread(GameView view) {
this.view = view;
}
public void setRunning(boolean run) {
running = run;
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
view.onDraw(c);
}
} finally {
if (c != null) {
view.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
Here is my layout:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/score"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Score:"
android:textSize="20dp" />
<Button
android:id="#+id/btnThread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:id="#+id/max"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginLeft="100dp"
android:text="Max:"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.3" >
<SurfaceView
android:id="#+id/snake_surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.3" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1" >
<Button
android:id="#+id/butUp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center"
android:text="UP" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/butLeft"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="LEFT" />
<Button
android:id="#+id/butRight"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="RIGHT" />
</RelativeLayout>
<Button
android:id="#+id/butDown"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center"
android:text="DOWN" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Your view in the layout is a SurfaceView, not a GameView. You need to change that:
<your.package.name.GameView
android:id="#+id/snake_surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.3" />
And replace your.package.name with the actual name of the package containing GameView.
Also, the line GameView gm = ... needs to go after setContentView.
And lastly, don't forget to call gm.invalidate() when you've modified the items that will be drawn!
I am using Camera feature in my app. Everything works fine but when the device gets locked/sleep, upon returning to the app the camera portion(SurfaceView) is just black. Below is my code. Can someone please identify the problem?
public class Activity_Camera extends Activity implements SurfaceHolder.Callback, Camera.AutoFocusCallback, Observer
{
// Surface vars
private SurfaceView preview;
private SurfaceHolder previewHolder;
// Camera vars
private Camera mCamera;
private boolean mPreviewRunning = false;
private boolean mCaptureFrame = false;
private int frame_number = 1;
private byte[] frame = new byte[1];
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preview = (SurfaceView) findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(this);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void onPause()
{
super.onPause();
if (mPreviewRunning)
{
mCamera.stopPreview();
mPreviewRunning = false;
}
mCamera.setPreviewCallback(null);
mCamera.release();
}
// implements SurfaceHolder.Callback
public void surfaceCreated(SurfaceHolder holder)
{
mCamera = Camera.open();
}
// implements SurfaceHolder.Callback
public void surfaceDestroyed(SurfaceHolder holder)
{
mPreviewRunning = false;
}
// implements Camera.AutoFocusCallback
public void onAutoFocus(boolean success, Camera camera)
{
}
PreviewCallback previewCallback = new PreviewCallback()
{
public void onPreviewFrame(byte[] data, Camera camera)
{
}
};
// implements SurfaceHolder.Callback
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
if (mPreviewRunning)
{
mCamera.stopPreview();
}
Camera.Parameters p = mCamera.getParameters();
p.setPreviewSize(640, 480);
mCamera.setParameters(p);
try
{
mCamera.setPreviewDisplay(holder);
} catch (IOException e)
{
e.printStackTrace();
}
mCamera.setPreviewCallback(previewCallback);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation)
{
case Surface.ROTATION_0:
degrees = 90;
break;
case Surface.ROTATION_90:
degrees = 0;
break;
case Surface.ROTATION_180:
degrees = 270;
break;
case Surface.ROTATION_270:
degrees = 180;
break;
}
Log.i("DEGREES ARE WHAT??", Integer.toString(degrees));
// mCamera.setDisplayOrientation(degrees);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
mPreviewRunning = true;
}
// implements Observer
// captures a frame when the compass listener says it is appropriate
public void update(Observable observable, Object data)
{
mCaptureFrame = true;
}
}
Please identify the issue, as I suspect something wrong with onPause(), it also gives me exception when I press back button after the black camera screen:
java.lang.RuntimeException: Method called after release()
on this line:
mCamera.setPreviewCallback(null); // (in onPause())
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#E6E5E6">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:id="#+id/tv_camera_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:textColor="#android:color/black"
android:text="URL goes here........"
android:layout_marginTop="3dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tv_speaknow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#ffffff"
android:layout_marginTop="3dp"
android:text="Speak Now"
android:textColor="#ff0000"
android:textStyle="bold"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/rl_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<SurfaceView
android:id="#+id/preview"
android:layout_width="480px"
android:layout_height="640px"
android:layout_alignParentBottom="true"/>
<Button
android:id="#+id/btn_take_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/camera"
android:layout_alignBottom="#+id/preview"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"/>
</RelativeLayout>
</LinearLayout>
If its the first time you are launching the app, the onPause really shouldn't be the problem.
But I'd move down the creation and such to onResume instead of onCreate.
And can i see your xml of the surfaceview?
Do you just want 1 picture?
if (mPreviewRunning)
{
mCamera.stopPreview();
}
And most people startPreview from onResume. try to move it up there..