安卓(Android) 怎么生成基于时间戳的照片文件uri

2019年10月27日23:04:40安卓(Android) 怎么生成基于时间戳的照片文件uri已关闭评论 368 1053字阅读3分30秒

1.简介

安卓(Android) 怎么生成基于时间戳的照片文件uri?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static Uri generateTimestampPhotoFileUri() {
        File photoFile = null;
        Uri photoFileUri = null;

        File outputDir = getPhotoDirectory();

        if (outputDir != null) {
            String timeStamp = new SimpleDateFormat("yyyyMMDD_HHmmss")
                    .format(new Date());
            String photoFileName = "IMG_" + timeStamp + ".jpg";

            photoFile = new File(outputDir, photoFileName);
            photoFileUri = Uri.fromFile(photoFile);
        }

        return photoFileUri;
    }

    public static File getPhotoDirectory() {
        File outputDir = null;
        String externalStorageState = Environment.getExternalStorageState();

        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            File picturesDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            outputDir = new File(picturesDir, "asdf");

            if (!outputDir.exists()) {
                if (!outputDir.mkdirs()) {
                    Log.e("CAMERA_HELPER",
                            "Unable to create output directory");
                    outputDir = null;
                }
            }
        }
        return outputDir;
    }
}

 
继续阅读
编程十万个怎么办