在build.gradle
添加依赖
//CameraX
def camerax_version = "1.0.0-alpha02"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
如图
在AndroidManifest.xml
添加权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
如图
在MainActivity
添加代码(全部替换)
package com.youyeetoo.r1_camerax;
import static androidx.camera.core.CameraX.bindToLifecycle;
import static androidx.camera.core.CameraX.unbindAll;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Rational;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.youyeetoo.r1_camerax.databinding.ActivityMainBinding;
import java.io.File;
public class MainActivity extends AppCompatActivity {
// Used to load the 'r1_camerax' library on application startup.
static {
System.loadLibrary("r1_camerax");
}
private ActivityMainBinding binding;
private final int REQUEST_CODE_PERMISSIONS = 101;
private final String [] REQUIRED_PERMISSIONS =new String[] {"android.permission.CAMERA","android.permission.WRITE_EXTERNAL_STORAGE"};
TextureView textureView;
ImageView cameraFlip;
private int backlensfacing = 0;
private int flashLamp = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Example of a call to a native method
// TextView tv = binding.sampleText;
// tv.setText(stringFromJNI());
textureView = findViewById(R.id.view_camera);
if(allPermissionsGranted())
{
startCamera(CameraX.LensFacing.BACK);
}
else {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
private void startCamera(CameraX.LensFacing CAMERA_ID)
{
unbindAll();
Rational aspectRatio = new Rational(textureView.getWidth(), textureView.getHeight());
Size screen = new Size(textureView.getWidth(),textureView.getHeight());
PreviewConfig pConfig;
Preview preview;
pConfig = new PreviewConfig.Builder().setLensFacing(CAMERA_ID).setTargetAspectRatio(aspectRatio).setTargetResolution(screen).build();
preview = new Preview(pConfig);
preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
@Override
public void onUpdated(Preview.PreviewOutput output)
{
ViewGroup parent = (ViewGroup)textureView.getParent();
parent.removeView(textureView);
parent.addView(textureView,0);
textureView.setSurfaceTexture(output.getSurfaceTexture());
updateTransform();
}
});
final ImageCaptureConfig imageCaptureConfig ;
imageCaptureConfig= new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MAX_QUALITY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).setLensFacing(CAMERA_ID).build();
final ImageCapture imgCap = new ImageCapture(imageCaptureConfig);
bindToLifecycle(this,preview, imgCap);
}
private void galleryAddPic(String currentFilePath){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File (currentFilePath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
//Toast.makeText(getBaseContext(), "saved to gallery",Toast.LENGTH_LONG).show();
}
private void updateTransform(){
Matrix mx = new Matrix();
float w = textureView.getMeasuredWidth();
float h = textureView.getMeasuredHeight();
float cX = w / 2f;
float cY = h / 2f;
int rotationDgr;
int rotation = (int)textureView.getRotation();
switch (rotation){
case Surface.ROTATION_0:
rotationDgr = 0;
break;
case Surface.ROTATION_90:
rotationDgr = 90;
break;
case Surface.ROTATION_180:
rotationDgr = 180;
break;
case Surface.ROTATION_270:
rotationDgr = 270;
break;
default: return;
}
mx.postRotate((float)rotationDgr, cX,cY);
textureView.setTransform(mx);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CODE_PERMISSIONS){
if (allPermissionsGranted()) {
startCamera(CameraX.LensFacing.BACK);
}
else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted()
{
for(String permission : REQUIRED_PERMISSIONS)
{
if(ContextCompat.checkSelfPermission(this, permission)!= PackageManager.PERMISSION_GRANTED)
{
return false;
}
}
return true;
}
private boolean checkCameraHardware(Context context)
{
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
private void toggleFrontBackCamera()
{
}
/**
* A native method that is implemented by the 'r1_camerax' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
如图
在activity_main.xml
添加ui(全部替换)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<TextureView
android:id="@+id/view_camera"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
如图
点击图标,编译运行
如图
点击r1_camerax可以看到摄像头画面被调出