[英]Camera Preview black in Android 7
I'm using a straight forwards Camera API , for backwards compatibility.为了向后兼容,我正在使用直接的Camera API 。 The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:相机视图本身被图像视图稍微覆盖,而我的 SurfaceChanged 执行此操作:
camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();
which works fine on all older devices.在所有旧设备上都可以正常工作。 I set the preview size to the largest available size earlier in surfaceCreated
.我在之前在surfaceCreated
预览大小设置为最大的可用大小。 However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).然而,在 Android 7.1 上,它突然变黑了(在 Nexus 6 和 Moto X Play 上,可能还有其他人 - 所以在不同的设备上)。 The SurfaceView
itself is greyed out in the Layout Inspector
( willNotDraw = true
), but VISIBLE
(and hardware accelerated).所述SurfaceView
本身是在灰色Layout Inspector
( willNotDraw = true
),但VISIBLE
(和硬件加速)。 Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.奇怪的是,我仍然可以拍照,没有预览的事件,并且预览回调中的数据包含图像。
At the same time I get the following log同时我得到以下日志
E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738
Has anybody else experienced a completely black image in Android 7?有没有其他人在 Android 7 中遇到过完全黑色的图像? Are there any easy fixes?有什么简单的修复方法吗? (Like drawing the content of data directly?) (喜欢直接绘制数据的内容?)
Black screen is appearing since you dont have camera permission on android 7 device由于您在 android 7 设备上没有相机权限,因此出现黑屏
Goto settings->apps->select your app->permissions->Enable camera permission and check转到设置->应用程序->选择您的应用程序->权限->启用相机权限并检查
You can also handle this inside your code你也可以在你的代码中处理这个
Add following permission to your manifest向您的清单添加以下权限
<uses-permission android:name="android.permission.CAMERA" />
For asking for permission you can call like this.要请求许可,您可以这样调用。
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
To check permission to access camera检查访问相机的权限
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
}
Now the Callback if the User has performed any action.现在回调,如果用户执行了任何操作。
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
Log.i("Camera", "G : " + grantResults[0]);
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
openCamera();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
if (ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.CAMERA)) {
showAlert();
} else {
}
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Here is complete example这是完整的例子
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
public static final String ALLOW_KEY = "ALLOWED";
public static final String CAMERA_PREF = "camera_pref";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (getFromPref(this, ALLOW_KEY)) {
showSettingsAlert();
} else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
showAlert();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
} else {
openCamera();
}
}
public static void saveToPreferences(Context context, String key,
Boolean allowed) {
SharedPreferences myPrefs = context.getSharedPreferences
(CAMERA_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean(key, allowed);
prefsEditor.commit();
}
public static Boolean getFromPref(Context context, String key) {
SharedPreferences myPrefs = context.getSharedPreferences
(CAMERA_PREF, Context.MODE_PRIVATE);
return (myPrefs.getBoolean(key, false));
}
private void showAlert() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
alertDialog.show();
}
private void showSettingsAlert() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startInstalledAppDetailsActivity(MainActivity.this);
}
});
alertDialog.show();
}
@Override
public void onRequestPermissionsResult
(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
boolean showRationale =
ActivityCompat.shouldShowRequestPermissionRationale
(this, permission);
if (showRationale) {
showAlert();
} else if (!showRationale) {
// user denied flagging NEVER ASK AGAIN
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
saveToPreferences(MainActivity.this, ALLOW_KEY, true);
}
}
}
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public static void startInstalledAppDetailsActivity(final Activity context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
private void openCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
Like @apk has said before, black screen is appearing because you are not handling permissions in your code.就像@apk 之前所说的那样,出现黑屏是因为您没有在代码中处理权限。 If you are working with targetSdkVersion 23
(and above) you will have to requests permissions from the user at run-time.如果您使用targetSdkVersion 23
(及更高版本),则必须在运行时向用户请求权限。
Previous comment explains you how to resolve it through SDK's operations directly, but I prefer use a great third party library for these cases: Karumi/Dexter之前的评论解释了如何直接通过 SDK 的操作来解决它,但我更喜欢在这些情况下使用一个很棒的第三方库: Karumi/Dexter
Check Android run-time camera permissions检查 Android 运行时相机权限
if permission is not allowed, the camera will shows blank screen.如果不允许,相机将显示黑屏。
for more details :更多细节 :
https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
i had this issue whit camera and quick fix whit adding this code to cameraPreview just add camera.stopPreview() before startPreview() .我在相机上遇到了这个问题,并快速修复了这个问题,只需在startPreview()之前添加camera.stopPreview()即可将此代码添加到 cameraPreview 中。
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
this.mCamera.stopPreview();
this.mCamera.setPreviewDisplay(surfaceHolder);
this.mCamera.startPreview();
} catch (IOException unused) {
Log.d("camera", "Error setting camera preview: " + unused.getMessage());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.