在后台Android中使用相机
我正试着把这张照片从照相机上取下来在后台Android中使用相机,android,background,android-camera,android-service,surfaceview,Android,Background,Android Camera,Android Service,Surfaceview,我正试着把这张照片从照相机上取下来 @Override public void onCreate() { super.onCreate(); //android.os.Debug.waitForDebugger(); myCamera=Camera.open(); SurfaceView dummy=new SurfaceView(getApplicationContext()); try { if(myCamera!=null)
@Override
public void onCreate() {
super.onCreate();
//android.os.Debug.waitForDebugger();
myCamera=Camera.open();
SurfaceView dummy=new SurfaceView(getApplicationContext());
try {
if(myCamera!=null)
{
myCamera.setPreviewDisplay(dummy.getHolder());
myCamera.setPreviewCallback(this);
Log.i(TAG,"myCamera is not null");
}
getFrames();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "setPreviewDisplay " + e);
}
myCamera.startPreview();
}
public void getFrames() {
new Thread(new Runnable() {
public void run() {
while(flag)
{
Log.i(TAG, "getFrames");
try{
//method();
takePictureNoPreview();
Thread.sleep(54);
} catch (Exception e) {
Log.e(TAG, "getFrames thread error: " + e);
}
}
myCamera.release();
}
}).start();
}
public void takePictureNoPreview(){
try{
Log.i(TAG,"takePictureNoPreview");
myCamera.takePicture(null, null, getJpegCallback())
} catch (Exception e) {
Log.e(TAG, "takePictureNoPreview " + e);
}
private PictureCallback getJpegCallback(){
PictureCallback jpeg=new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
Log.i(TAG,"getJpegCallback");
FileOutputStream(String.format("/sdcard/RealSpeaker/%d.jpg", System.currentTimeMillis()));
FileOutputStream os = new FileOutputStream(String.format("/sdcard/Sample/%d.jpg", System.currentTimeMillis()));
os.write(data);
os.close();
} catch (IOException e) {
//do something about it
}
}
};
return jpeg;
}
问题是getJpegCallback-around方法不正确:文件夹中没有日志和图像
当我调试应用程序时,TAG-getJpegCallback不会显示在LogCat中,但是TAG-takePictureReview会显示出来。关闭应用程序后,摄像头不允许显示这没有问题。怎么了?我在开发时遇到了这个问题。我想捕捉图像,即使应用程序是在背景或前景。我试了几个星期,但没有成功。使用相机捕捉照片意味着显示其预览 五,。六,。您必须使用来显示预览 当你关闭应用程序或你的应用程序进入后台时,SurfaceView的表面将被破坏。这就是为什么我认为这是不可能的 如果你找到其他方法,请在这里发布
希望这对您有所帮助。我在开发时遇到了这个问题。我想捕捉图像,即使应用程序是在背景或前景。我试了几个星期,但没有成功。使用相机捕捉照片意味着显示其预览 五,。六,。您必须使用来显示预览 当你关闭应用程序或你的应用程序进入后台时,SurfaceView的表面将被破坏。这就是为什么我认为这是不可能的 如果你找到其他方法,请在这里发布
希望这对您有所帮助。从API 11开始,您可以使用SurfaceTexture,而不是使用SurfaceView的SurfaceHolder。然后,使用Camera.setPreviewTexture而不是Camera.setPreviewDisplay进行设置 在不同设备上的服务中,它对我来说效果很好
回答并讨论这一点。从API 11开始,您可以使用SurfaceTexture,而不是使用SurfaceView的SurfaceHolder。然后,使用Camera.setPreviewTexture而不是Camera.setPreviewDisplay进行设置
public class TakePicture extends Activity implements SurfaceHolder.Callback {
// a variable to store a reference to the Image View at the main.xml file
// private ImageView iv_image;
// a variable to store a reference to the Surface View at the main.xml file
private SurfaceView sv;
// a bitmap to display the captured image
private Bitmap bmp;
FileOutputStream fo;
// Camera variables
// a surface holder
private SurfaceHolder sHolder;
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private String FLASH_MODE;
private boolean isFrontCamRequest = false;
private Camera.Size pictureSize;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// check if this device has a camera
if (checkCameraHardware(getApplicationContext()))
{
// get the Image View at the main.xml file
// iv_image = (ImageView) findViewById(R.id.imageView);
// get the Surface View at the main.xml file
Bundle extras = getIntent().getExtras();
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = true;
System.out.println("front_cam_req :"+front_cam_req);
sv = (SurfaceView) findViewById(R.id.camera_preview);
// Get a surface
sHolder = sv.getHolder();
// add the callback interface methods defined below as the Surface
// View
// callbacks
sHolder.addCallback(this);
// tells Android that this surface will have its data constantly
// replaced
if (Build.VERSION.SDK_INT < 11)
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
else {
// display in long period of time
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
.show();
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Check if this device has front camera */
private boolean checkFrontCamera(Context context)
{
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT))
{
// this device has front camera
return true;
}
else
{
// no front camera on this device
return false;
}
}
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
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// get camera parameters
if (mCamera != null) {
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
// sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bmp != null)
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(),
"OneSheeld");
if (!imagesFolder.exists())
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder,
System.currentTimeMillis() + ".jpg");
// write the bytes in file
try {
fo = new FileOutputStream(image);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
}
// remember close de FileOutput
try {
fo.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment
.getExternalStorageDirectory())));
} catch (IOException e) {
// TODO Auto-generated catch block
}
if (mCamera != null) {
mCamera.stopPreview();
// release the camera
mCamera.release();
}
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_LONG)
.show();
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
TakePicture.this.finish();
}
};
mCamera.takePicture(null, null, mCall);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.
if (isFrontCamRequest)
{
//Toast.makeText(getApplicationContext()," isFrontCamRequest()",Toast.LENGTH_LONG).show();
System.out.println("isFrontCamRequest 1");
// set flash 0ff
FLASH_MODE = "off";
// only for gingerbread and newer versions
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD)
{
System.out.println("isFrontCamRequest 2");
mCamera = openFrontFacingCameraGingerbread();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera = null;
Toast.makeText(getApplicationContext(),"API dosen't support front camera",Toast.LENGTH_LONG).show();
TakePicture.this.finish();
}
}
else
{
System.out.println("isFrontCamRequest 3");
if (checkFrontCamera(getApplicationContext()))
{
mCamera = openFrontFacingCameraGingerbread();
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException exception)
{
mCamera = null;
Toast.makeText(getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
TakePicture.this.finish();
}
}/*
* else { // API dosen't support front camera or no front camera
* Log.d("Camera",
* "API dosen't support front camera or no front camera");
* Toast.makeText( getApplicationContext(),
* "API dosen't support front camera or no front camera",
* Toast.LENGTH_LONG).show();
*
* finish(); }
*/
}
}
else
{
System.out.println("isFrontCamRequest 4");
mCamera = getCameraInstance();
try
{
mCamera.setPreviewDisplay(holder);
}
catch (Exception exception) {
mCamera = null;
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// stop the preview
/*
* mCamera.stopPreview(); // release the camera mCamera.release();
*/
// unbind the camera from this object
mCamera = null;
}
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("Camera",
"Camera failed to open: " + e.getLocalizedMessage());
Toast.makeText(getApplicationContext(),
"Front Camera failed to open", Toast.LENGTH_LONG)
.show();
}
}
}
return cam;
}
@Override
protected void onDestroy() {
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
super.onDestroy();
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
}
在不同设备上的服务中,它对我来说效果很好
回答并讨论这一点。你可以试试这个
public class TakePicture extends Activity implements SurfaceHolder.Callback {
// a variable to store a reference to the Image View at the main.xml file
// private ImageView iv_image;
// a variable to store a reference to the Surface View at the main.xml file
private SurfaceView sv;
// a bitmap to display the captured image
private Bitmap bmp;
FileOutputStream fo;
// Camera variables
// a surface holder
private SurfaceHolder sHolder;
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private String FLASH_MODE;
private boolean isFrontCamRequest = false;
private Camera.Size pictureSize;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// check if this device has a camera
if (checkCameraHardware(getApplicationContext()))
{
// get the Image View at the main.xml file
// iv_image = (ImageView) findViewById(R.id.imageView);
// get the Surface View at the main.xml file
Bundle extras = getIntent().getExtras();
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = true;
System.out.println("front_cam_req :"+front_cam_req);
sv = (SurfaceView) findViewById(R.id.camera_preview);
// Get a surface
sHolder = sv.getHolder();
// add the callback interface methods defined below as the Surface
// View
// callbacks
sHolder.addCallback(this);
// tells Android that this surface will have its data constantly
// replaced
if (Build.VERSION.SDK_INT < 11)
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
else {
// display in long period of time
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
.show();
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Check if this device has front camera */
private boolean checkFrontCamera(Context context)
{
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT))
{
// this device has front camera
return true;
}
else
{
// no front camera on this device
return false;
}
}
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
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// get camera parameters
if (mCamera != null) {
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
// sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bmp != null)
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(),
"OneSheeld");
if (!imagesFolder.exists())
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder,
System.currentTimeMillis() + ".jpg");
// write the bytes in file
try {
fo = new FileOutputStream(image);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
}
// remember close de FileOutput
try {
fo.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment
.getExternalStorageDirectory())));
} catch (IOException e) {
// TODO Auto-generated catch block
}
if (mCamera != null) {
mCamera.stopPreview();
// release the camera
mCamera.release();
}
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_LONG)
.show();
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
TakePicture.this.finish();
}
};
mCamera.takePicture(null, null, mCall);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.
if (isFrontCamRequest)
{
//Toast.makeText(getApplicationContext()," isFrontCamRequest()",Toast.LENGTH_LONG).show();
System.out.println("isFrontCamRequest 1");
// set flash 0ff
FLASH_MODE = "off";
// only for gingerbread and newer versions
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD)
{
System.out.println("isFrontCamRequest 2");
mCamera = openFrontFacingCameraGingerbread();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera = null;
Toast.makeText(getApplicationContext(),"API dosen't support front camera",Toast.LENGTH_LONG).show();
TakePicture.this.finish();
}
}
else
{
System.out.println("isFrontCamRequest 3");
if (checkFrontCamera(getApplicationContext()))
{
mCamera = openFrontFacingCameraGingerbread();
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException exception)
{
mCamera = null;
Toast.makeText(getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
TakePicture.this.finish();
}
}/*
* else { // API dosen't support front camera or no front camera
* Log.d("Camera",
* "API dosen't support front camera or no front camera");
* Toast.makeText( getApplicationContext(),
* "API dosen't support front camera or no front camera",
* Toast.LENGTH_LONG).show();
*
* finish(); }
*/
}
}
else
{
System.out.println("isFrontCamRequest 4");
mCamera = getCameraInstance();
try
{
mCamera.setPreviewDisplay(holder);
}
catch (Exception exception) {
mCamera = null;
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// stop the preview
/*
* mCamera.stopPreview(); // release the camera mCamera.release();
*/
// unbind the camera from this object
mCamera = null;
}
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("Camera",
"Camera failed to open: " + e.getLocalizedMessage());
Toast.makeText(getApplicationContext(),
"Front Camera failed to open", Toast.LENGTH_LONG)
.show();
}
}
}
return cam;
}
@Override
protected void onDestroy() {
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
super.onDestroy();
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
}
Intent translucent = new Intent(getApplication(),
TakePicture.class);
translucent.putExtra("FLASH", "on");
startActivity(translucent);
Toast.makeText(getApplicationContext(), "Started Capture", 500).show();
<SurfaceView
android:id="@+id/camera_preview"
android:layout_width="1dp"
android:layout_height="1dp" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
就这么做吧,这对我有用。
希望有帮助。你可以试试这个
Intent translucent = new Intent(getApplication(),
TakePicture.class);
translucent.putExtra("FLASH", "on");
startActivity(translucent);
Toast.makeText(getApplicationContext(), "Started Capture", 500).show();
<SurfaceView
android:id="@+id/camera_preview"
android:layout_width="1dp"
android:layout_height="1dp" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
就这么做吧,这对我有用。
希望有帮助。解决方案似乎很晚了,但仍然..实际上,我们可以通过使用Windows Manager在onCreate中创建并扩展布局..和setVisibilityView.INVISIBLE中从服务获得UI
您还可以参考示例应用程序,并在必要时提供帮助。解决方案似乎很晚了,但仍然..实际上,我们可以通过usgin WindowManager在onCreate中创建并扩展布局..和setVisibilityView.INVISIBLE中从服务获得UI
你也可以参考一个示例应用程序,如果有必要,也可以参与其中。我不知道这是否已经晚了,但对于仍在搜索的用户,请尝试此应用程序。我不知道这是否已经晚了,但是对于仍在搜索的用户,请尝试此应用程序。我的经验是,我需要在布局中进行实际的SurfaceView以进行搜索图片,所以我添加了一个SurfaceView,高度=20dp,marginTop=-100dp,或者其他一些东西来移动它,但它仍然存在于布局中。也许你应该试试这样的。另一个想法是:您不应该在回调的surfaceCreated/Changed方法中调用setPreviewDisplay和startPreview吗?好的。我是first Variantar你是否尝试在背景中录制视频我经历过的是,我需要在版面中使用一个实际的SurfaceView来拍照,所以我添加了一个SurfaceView,高度=20dp,边缘=100dp,或者其他一些东西来将其移出视线,但它仍然存在于版面中。也许你应该试试这样的。另一个想法是:您不应该在回调的surfaceCreated/Changed方法中调用setPreviewDisplay和startPreview吗?好的。我是第一个,你想在后台录视频吗?你试过这样的吗?->->使用此窗口作为预览显示,显示自定义警报窗口,不包含任何内容,但surfaceview不可见或在屏幕外某处?->@damian谢谢你让我知道…我今天早上试过了,它成功了…我会为我的应用程序试一试。你有没有可能扩展代码来完成这个?我弹出了测试语言,但在没有FCing的情况下无法让相机运行。您尝试过类似的方法吗?->->使用此窗口作为预览显示,显示自定义警报窗口,不包含任何内容,但surfaceview不可见或在屏幕外某处?->@damian谢谢你让我知道…我今天早上试过了,它成功了…我会为我的应用程序试一试。你有没有可能扩展代码来完成这个?我有测试语言弹出,但不能让相机在没有FCing的情况下运行。请给出一些细节。请给出一些细节。