要将相机拍摄的照片保存到特定文件夹并在设备画廊中查看,可以按照以下步骤进行操作:
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST_CODE = 1;
private File imageFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureButton = findViewById(R.id.capture_button);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
capturePhoto();
}
});
}
private void capturePhoto() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// 创建保存照片的文件
imageFile = createImageFile();
// 将照片保存到文件中
if (imageFile != null) {
Uri photoUri = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
}
}
private File createImageFile() {
// 创建一个文件名
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + ".jpg";
// 获取存储照片的文件夹
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApp");
// 如果文件夹不存在,则创建文件夹
if (!storageDir.exists()) {
storageDir.mkdirs();
}
// 创建保存照片的文件
File imageFile = new File(storageDir, imageFileName);
return imageFile;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
// 将照片添加到设备的图库中
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(imageFile);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
}
file_paths.xml
,放在res/xml
文件夹下,内容如下:
标签内:
...
现在,当用户点击拍照按钮时,将会启动相机应用程序,拍摄完照片后,照片将保存在指定文件夹中,并在设备的画廊中可见。