美文网首页
x、Android保存图片至相册原生代码

x、Android保存图片至相册原生代码

作者: 万士辰 | 来源:发表于2017-05-17 14:26 被阅读159次
    package com.xxx.NativeCode;
    
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Environment;
    import android.text.format.Time;
    
    import com.unity3d.player.UnityPlayer;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * Created by wanshichen on 2017/3/16.
     */
    
    public class NativeCodeHandle {
        public static void SaveImageToAlbum(String fromPath) {
            Time t = new Time();
            t.setToNow();
            final String toPath = Environment.getExternalStorageDirectory() + String.format("/DCIM/Camera/IMG_xxx_%d%d%d_%d%d%d.jpg", t.year, t.month, t.monthDay, t.hour, t.minute, t.second);
            CopyFileTo(fromPath, toPath);
            UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    scanPhotos(toPath, UnityPlayer.currentActivity);
                    AlertDialog.Builder builder = new AlertDialog.Builder(UnityPlayer.currentActivity)
                            .setTitle("提示")
                            .setMessage("保存成功")
                            .setPositiveButton("确定", null);
                    builder.show();
                }
            });
        }
    
        public static void CopyFileTo(String fromPath, String toPath) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(fromPath);
                fos = new FileOutputStream(toPath);
                byte[] buffer = new byte[1024];
                int byteread = 0;
                while ((byteread = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteread);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
        public static void scanPhotos(String filePath, Context context) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(new File(filePath)));
            context.sendBroadcast(intent);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:x、Android保存图片至相册原生代码

          本文链接:https://www.haomeiwen.com/subject/ciedxxtx.html