Unity 录屏截屏到Android相册,支持鸿蒙

Unity端截屏代码

  string date = System.DateTime.Now.ToString("dd-MM-yy");
  string fileName="XXXXX";
  string screenshotFilename = fileName + "_"+ date + ".png";
    if (Application.platform == RuntimePlatform.Android)
        {
	        if (UnityCallAndroidByJavaManager.Intance.isHarmonyOs())
	        {
		        string androidPath = "/mnt/sdcard/DCIM/" + albumName + "/" + screenshotFilename;
		        string path = Application.persistentDataPath + androidPath;
		        string pathonly = Path.GetDirectoryName(path);

		        if (!Directory.Exists(pathonly))
		        {
			        Directory.CreateDirectory(pathonly);
		        }
		        ScreenCapture.CaptureScreenshot(androidPath);

		        yield return new WaitForSeconds(.5f);
	        
		        UnityCallAndroidByJavaManager.Intance.SaveImageOnlyHarmonyOs(path);
	        }
	        else
	        {
		       string androidPath = "/../../../../DCIM/" + albumName + "/" + screenshotFilename;
            
		        string path = Application.persistentDataPath + androidPath;
            
		        string pathonly = Path.GetDirectoryName(path);

		        if (!Directory.Exists(pathonly))
		        {
			        Directory.CreateDirectory(pathonly);
		        }
		        ScreenCapture.CaptureScreenshot(androidPath);
		        AndroidJavaClass obj = new AndroidJavaClass("com.ryanwebb.androidscreenshot.MainActivity");

		        while (!photoSaved)
		        {
			        photoSaved = obj.CallStatic<bool>("scanMedia", path);
			        yield return new WaitForSeconds(.5f);
		        }
	        }

Unity需要的Android Jar及Java代码(由于之前是找的一个Jar库因不支持鸿蒙所以自己动手二次开发的Java调用库)

Unity JAR库(支持Android系统)

需要的Unity调用的Java库的下载链接

下面是部分Java库的代码展示

	  /**
     * 是否为鸿蒙系统
     *
     * @return true为鸿蒙系统
     */
    public  boolean isHarmonyOs() {
        try {
            Class<?> buildExClass = Class.forName("com.huawei.system.BuildEx");
            Object osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass);
            return "Harmony".equalsIgnoreCase(osBrand.toString());
        } catch (Throwable x) {
            return false;
        }
    }
    /**
     * 刷新指定文件
     */
    public void ScenMediaFile(String MediaPath, Context context) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(MediaPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
        Toast.makeText(context, "已保存到相册", Toast.LENGTH_SHORT).show();
    }
    private void ScenMediaFileByUrl(Uri MediaPath, Context context) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,MediaPath);
        mediaScanIntent.setData(MediaPath);
        context.sendBroadcast(mediaScanIntent);
        Toast.makeText(context, "已保存到相册", Toast.LENGTH_SHORT).show();

    }
    /**
     * 刷新指定文件夹
     */
    public void ScenMediaDir(String MediaPath, Context context) {

        final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";
        Intent mediaScanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
        File f = new File(MediaPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);

    }

    /**
     * API 29及以下保存图片到相册的方法
     *
     * @param toBitmap 要保存的图片
     */
    private void saveImage(Context context, Bitmap toBitmap) {
        String insertImage = MediaStore.Images.Media.insertImage(context.getContentResolver(), toBitmap, toBitmap.toString(), "");
        if (!TextUtils.isEmpty(insertImage)) {

            Toast.makeText(context, insertImage, Toast.LENGTH_SHORT).show();

            File f = new File(insertImage);
            Uri contentUri = Uri.fromFile(f);
            ScenMediaFileByUrl(contentUri, context);
        }
    }

    /**
     * API29 中的最新保存图片到相册的方法
     */
    private void saveImage29(Context context, Bitmap toBitmap) {
        Uri insertUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        try {
            OutputStream outputStream = context.getContentResolver().openOutputStream(insertUri, "rw");
            if (toBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
                Log.e("保存成功", "success");
            } else {
                Log.e("保存失败", "fail");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ScenMediaFileByUrl(insertUri, context);

    }

Unity录屏代码

学习使用的NativeGallery录屏插件下载

#Unity调用Java库的代码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;

public class UnityCallAndroidByJavaManager : MonoBehaviour
{
    private AndroidJavaObject jo;

    private AndroidJavaClass act;

    private AndroidJavaObject actObj;

    public static UnityCallAndroidByJavaManager Intance;

    private void Awake()
    {
        Intance = this;
    }
    private void CheckInit()
    {
        jo = null;
        act = null;
        actObj = null;
        jo = new AndroidJavaObject("com.test.MainActivity");
        act = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        actObj = act.GetStatic<AndroidJavaObject>("currentActivity");
    }

    /// <summary>
    /// 是否是鸿蒙系统
    /// </summary>
    public bool isHarmonyOs()
    {
        CheckInit();
        var reslut = jo.Call<bool>("isHarmonyOs");
        return reslut;
    }

    /// <summary>
    /// 刷新指定文件到媒体库
    /// </summary>
    public void ScenMediaFile(string FilePath)
    {
        CheckInit();
        jo.Call("ScenMediaFile", FilePath, actObj);
    }

    /// <summary>
    /// 保存图片至相册 只用于鸿蒙
    /// </summary>
    public void SaveImageOnlyHarmonyOs(string photoPath)
    {
        Debug.Log(photoPath);
        CheckInit();
        jo.Call("SaveImageByOS",actObj, photoPath);
    }

    /// <summary>
    /// 保存视频至相册 只用于鸿蒙
    /// </summary>
    public void SaveVideoOnlyHarmonyOs(string VideoPath)
    {
        CheckInit();
        jo.Call("saveVideoToLocal", VideoPath, actObj);
    }
}

如有兴趣,欢迎留言一起讨论

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值