目前安卓startActivityForResult已棄用,所以替用ActivityResultLauncher的方法開啟相機,目前想將拍攝照片能暫存在手機當前頁面,不知道如何實現?
AndroidManifest.xml
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Activity
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private String currentPhotoPath;
private ActivityResultLauncher<Uri> takePictureLauncher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Button takePictureButton = findViewById(R.id.takePictureButton);
takePictureLauncher = registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
if (result) {
// 照片拍攝成功,顯示照片
imageView.setImageURI(Uri.parse(currentPhotoPath));
}
});
takePictureButton.setOnClickListener(v -> {
// 啟動相機
try {
Uri photoUri = createImageFile();
takePictureLauncher.launch(photoUri);
} catch (IOException e) {
e.printStackTrace();
}
});
}
private Uri createImageFile() throws IOException {
// 使用時間戳生成文件名
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return FileProvider.getUriForFile(this, "com.example.android.fileprovider", image);
}
}
在 activity_main.xml 中加入 ImageView 和一個 Button:
<LinearLayout
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"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_height="300dp"
android:scaleType="centerCrop"
app:srcCompat="@android:drawable/ic_menu_camera" />
<Button
android:id="@+id/takePictureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照" />
</LinearLayout>