Android - Getting camera LED to strobe with handler? - android

I am using a timed alert (working fine) to try and run code that will quickly switch camera flash LED between off and on positions.
I'm trying to use a handler to switch between the two modes but cannot seem to get it to run.
I was wondering if someone could suggest another way to strobe the camera LED or if they could try to find something wrong with my code.
Help would be greatly appreciated, I'm really new to android programming.
Here's the code:
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Handler;
public class MyAlert extends Activity {
private Handler mHander = new Handler();
private boolean mActive = false;
private boolean mSwap = true;
private Camera camera;
final Parameters p = camera.getParameters();
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mSwap) {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera = Camera.open();
camera.setParameters(p);
camera.startPreview();
mSwap = false;
mHander.postDelayed(mRunnable, 20);
} else {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera = Camera.open();
camera.setParameters(p);
camera.stopPreview();
mSwap = true;
mHander.postDelayed(mRunnable, 100);
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startStrobe();
}
private void startStrobe() {
mActive = true;
mHander.post(mRunnable);
}
};

AFAIR, stopping preview and releasing the camera is enough to switch flash off. But real problem is that devices behave differently and not always as advertised.

Related

Why my android code is of large size?

Following is the code for my app for a flash light
Its size comes out to be 1.4 MB which is too huge .
So i used progaurd to reduce size which ends up in 750 KB which is still huge as compared to code i am using.
Why the size is large ? and how to reduce it ? or i have made some mistake
package com.example.torch;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button power;
int flag=0;
public Camera camera;
private boolean hasFlash;
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onStop() {
super.onStop();
try{
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power=(Button)findViewById(R.id.button1);
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.show();
return;
}
camera = Camera.open();
Camera.Parameters p = camera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
flag = 1;
power.setText("Power On");
power.setBackgroundColor(Color.BLUE);
power.setTextColor(Color.WHITE);
power.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (flag==0) {
camera = Camera.open();
Camera.Parameters p = camera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
flag = 1;
power.setText("Power On");
power.setBackgroundColor(Color.BLUE);
}
else
{
camera.stopPreview();
camera.release();
camera = null;
flag=0;
power.setText("Power Off");
power.setBackgroundColor(Color.BLACK);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
You are extending AppCompatActivity, this means that your project includes Android Support Library v7, if you don't care about material look on old Android versions, you can simply remove it. Check your build.gradle file to see which libraries are included as those libraries will make your apk file bigger.
Other causes of a large apk file might be:
Drawables
Assets

Getting the torch to glow?

My objective is as simple as to have my own flashlight app; I have researched both the android developer site and stackoverflow quite thoroughly but seem to lack the connecting bits:
package my.torch;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.CompoundButton;
public class MainActivity extends Activity {
/* public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
*/
Camera mCamera;
CompoundButton mTorch;
Parameters camParams;
private Context context;
AlertDialog.Builder builder;
AlertDialog alertDialog;
public SurfaceView surfaceView;
public SurfaceHolder surfaceHolder;
public String flashMode = null;
/** A safe way to get an instance of the Camera object. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.mysurface);
surfaceHolder = surfaceView.getHolder();
context = MainActivity.this;
if(context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)){
mTorch = (CompoundButton) findViewById(R.id.toggleButton1);
}
else{
// should use Dialog
// tell the user that he has no camera
//showDialog(context, FLASH_NOT_SUPPORTED);
}
final Camera mCamera = Camera.open(0);
mTorch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("mTorch", "on");
Parameters camParams = mCamera.getParameters();
// params.setFlashMode( Parameters.FLASH_MODE_OFF )
camParams.setFlashMode( Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(camParams);
mCamera.startPreview();
flashMode = camParams.getFlashMode();
Log.e("mTorch", flashMode );
// The toggle is enabled
} else {
// The toggle is disabled
Log.e("mTorch", "off");
Parameters camParams = mCamera.getParameters();
// params.setFlashMode( Parameters.FLASH_MODE_OFF )
camParams.setFlashMode( Parameters.FLASH_MODE_OFF);
mCamera.setParameters(camParams);
mCamera.stopPreview();
flashMode = camParams.getFlashMode();
Log.e("mTorch", flashMode );
}
}
});
//mCamera.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onDestroy() {
super.onDestroy();
if (mCamera != null) {
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(camParams);
mCamera.stopPreview();
mCamera.release();
}
}
}
The logging happily reports that the flashmode is torch or off as intended, however: The flash does not torch at all.
I read that I needed a surfaceview so I added it but with 0 height.
As I did collect bits and pieces here and there the code is probably not beautiful, my apologies.
Any idea on what I'm missing out?
(this is for a Nexus 5, 4.4.2)
Did you add permission to access camera in your manifest file?
uses-permission android:name="android.permission.CAMERA"

FLASH_MODE_TORCH working/not working

I wanted to build a flashlight app using the following code.
It's working on a friend's HTC Desire HD, but it isn't on my RAZR and a friend's Galaxy Nexus.
I also tried the solution with focus_mode_infinity, but there's still no success.
package com.example.flashlight;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Camera camera = null;
Parameters parameters;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button OnOff = (Button)findViewById(R.id.Switch);
OnOff.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
if(camera == null) {
camera = Camera.open();
camera.startPreview();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
camera.setParameters(parameters);
}
else {
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(parameters);
camera.release();
camera = null;
}
}
});
}}
I think FLASH_MODE_TORCH is not supported by RAZR, I've had the same issue with a customer reporting the same problem for one app (Flash not flashing).
What I suggest you is before setting the parameter to check if its supported:
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
// Mode supported good to go
}
after setting parameters of the camera use the below method:
camera.startPreview();
here camera is your Camera object.

How to record video from background of application : Android

I am developing an application which will be able to record video from background of application by using Service.
Problem description :
In my application recording will be scheduled. If user want to record video from 1 PM to 3 PM, he will schedule the task and can exit from application. Application will automatically start recording at 1PM to 3PM.
What I did yet :
I googled about my query but didn't get solution. Many articles say that it is not possible. But in Google Play there are some applications (for eg MyCar Recorder) which can record video from background of application.
I got an article about same but its not working.
What is the way to implement this functionality?
1- I have created a activity to start service like this:
package com.android.camerarecorder;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class CameraRecorder extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Recorder";
public static SurfaceView mSurfaceView;
public static SurfaceHolder mSurfaceHolder;
public static Camera mCamera ;
public static boolean mPreviewRunning;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(CameraRecorder.this, RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
finish();
}
});
Button btnStop = (Button) findViewById(R.id.StopService);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(CameraRecorder.this, RecorderService.class));
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
2 - Now I have created a service to record the video in background like this:
package com.android.camerarecorder;
import java.io.IOException;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class RecorderService extends Service {
private static final String TAG = "RecorderService";
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private static Camera mServiceCamera;
private boolean mRecordingStatus;
private MediaRecorder mMediaRecorder;
#Override
public void onCreate() {
mRecordingStatus = false;
//mServiceCamera = CameraRecorder.mCamera;
mServiceCamera = Camera.open(1);
mSurfaceView = CameraRecorder.mSurfaceView;
mSurfaceHolder = CameraRecorder.mSurfaceHolder;
super.onCreate();
if (mRecordingStatus == false)
startRecording();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
stopRecording();
mRecordingStatus = false;
super.onDestroy();
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
//mServiceCamera = Camera.open();
Camera.Parameters params = mServiceCamera.getParameters();
mServiceCamera.setParameters(params);
Camera.Parameters p = mServiceCamera.getParameters();
final List<Size> listSize = p.getSupportedPreviewSizes();
Size mPreviewSize = listSize.get(2);
Log.v(TAG, "use: width = " + mPreviewSize.width
+ " height = " + mPreviewSize.height);
p.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
p.setPreviewFormat(PixelFormat.YCbCr_420_SP);
mServiceCamera.setParameters(p);
try {
mServiceCamera.setPreviewDisplay(mSurfaceHolder);
mServiceCamera.startPreview();
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
mServiceCamera.unlock();
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(mServiceCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mMediaRecorder.setOutputFile("/sdcard/video.mp4");
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mPreviewSize.width, mPreviewSize.height);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();
mRecordingStatus = true;
return true;
} catch (IllegalStateException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
return false;
} catch (IOException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
try {
mServiceCamera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaRecorder.stop();
mMediaRecorder.reset();
mServiceCamera.stopPreview();
mMediaRecorder.release();
mServiceCamera.release();
mServiceCamera = null;
}
}
It will create a file video.mp4 in your sd card. you may change the code for adding more functionality but the basic functionality is achieved through this code i.e. record video in background.
NOTE: I have started the service through button click in activity but you can start it through any other way also like broadcastreceiver etc.
Yes, you can record the background video like this:
First, create a video app using service. Do not set its view so that it will not be visible.
If you are doing it in service then that is better because...
Second, you can use the AlarmManager for setting the alarm of particular time and then at that time, by using intent, start your service again. For stopping your app you can use AlarmManager, as well.

Why is my Android app camera preview running out of memory on my AVD?

I have yet to try this on an actual device, but expect similar results.
Anyway, long story short, whenever I run my app on the emulator, it crashes due to an out of memory exception.
My code really is essentially the same as the camera preview API demo from google, which runs perfectly fine.
The only file in the app (that I created/use) is as below-
package berbst.musicReader;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/*********************************
* Music Reader v.0001
* Still VERY under construction.
* #author Bryan
*
*********************************/
public class MusicReader extends Activity {
private MainScreen main;
#Override
//Begin activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main = new MainScreen(this);
setContentView(main);
}
class MainScreen extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder sHolder;
Camera cam;
MainScreen(Context context) {
super(context);
//Set up SurfaceHolder
sHolder = getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// Open the camera and start viewing
cam = Camera.open();
try {
cam.setPreviewDisplay(holder);
} catch (IOException exception) {
cam.release();
cam = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Kill all our crap with the surface
cam.stopPreview();
cam.release();
cam = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Modify parameters to match size.
Camera.Parameters params = cam.getParameters();
params.setPreviewSize(w, h);
cam.setParameters(params);
cam.startPreview();
}
}
}
Make sure the camera permission is added in AndroidManifest.xml. Apparently you'll get an out of memory exception if you don't (for some bizarre reason). It worked for me, anyway.

Categories

Resources