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);
    }
}

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

原文地址:https://blog.csdn.net/m0_37382999/article/details/124880049

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读1.4k次。被@Observed装饰的类,可以被观察到属性的变化;子组件中@ObjectLink装饰器装饰的状态变量用于接收@Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被@Observed装饰的项,或者是class object中是属性,这个属性同样也需要被@Observed装饰。单独使用@Observed是没有任何作用的,需要搭配@ObjectLink或者@Prop使用。_鸿蒙ark对象数组
文章浏览阅读1k次。Harmony OS_harmonyos创建数据库
文章浏览阅读1.1k次,点赞25次,收藏23次。自定义组件Header.ets页面(子组件)//自定义组件@Component//组件声明private title:ResourceStr//接收的参数build(){Row() {index.ets(父组件)//导入自定义组件@Entry@Componentbuild() {Column() {/*** 1. 自定义组件调用-----自定义组件------* 2. 在调用的组件上设置样式*/ShopTitle({ title: '商品列表' })
文章浏览阅读952次,点赞11次,收藏25次。ArkUI是一套构建分布式应用界面的声明式UI开发框架。它使用极简的UI信息语法、丰富的UI组件、以及实时界面预览工具,帮助您提升移动应用界面开发效率30%。您只需使用一套ArkTS API,就能在Android、iOS、鸿蒙多个平台上提供生动而流畅的用户界面体验。_支持ios 安卓 鸿蒙next的跨平台方案
文章浏览阅读735次。​错误: 找不到符号符号: 变量 Layout_list_item位置: 类 ResourceTable_错误: 找不到符号 符号: 变量 resourcetable 位置: 类 mainabilityslice
文章浏览阅读941次,点赞23次,收藏21次。harmony ARKTS base64 加解密_鸿蒙 鸿蒙加解密算法库
文章浏览阅读860次,点赞21次,收藏24次。使用自定义布局,实现子组件自动换行功能。图1自定义布局的使用效果创建自定义布局的类,并继承ComponentContainer,添加构造方法。//如需支持xml创建自定义布局,必须添加该构造方法实现ComponentContainer.EstimateSizeListener接口,在onEstimateSize方法中进行测量。......@Override//通知子组件进行测量//关联子组件的索引与其布局数据idx++) {//测量自身。_鸿蒙javaui
文章浏览阅读917次,点赞25次,收藏25次。这里需要注意的是,真机需要使用华为侧提供的测试机,测试机中会安装纯鸿蒙的系统镜像,能够体验到完整的鸿蒙系统功能,纯鸿蒙应用目前还不能完美地在 HarmonyOS 4.0 的商用机侧跑起来。当前,真机调试需要使用华为侧提供的测试机,测试机中会安装纯鸿蒙的系统镜像,能够体验到完整的鸿蒙系统功能,纯鸿蒙应用目前还不能完美地在 HarmonyOS 4.0 的商用机侧跑起来。另外,由于样式的解析是基于组件文件的纬度的,因此样式文件只能应用于被其引用的组件文件中,而不能跨文件应用,并且样式文件也只支持类选择器。_鸿蒙 小程序
文章浏览阅读876次,点赞17次,收藏4次。2. HarmonyOS应用开发DevEcoStudio准备-1HUAWEI DevEco Studio为运行在HarmonyOS和OpenHarmony系统上的应用和服务(以下简称应用/服务)提供一站式的开发平台。
文章浏览阅读811次。此对象主要映射JSON数组数据,比如服务器传的数据是这样的。_arkts json
文章浏览阅读429次。鸿蒙小游戏-数字华容道_华为鸿蒙手机自带小游戏
文章浏览阅读1.1k次,点赞24次,收藏19次。Ability是应用/服务所具备的能力的抽象,一个Module可以包含一个或多个Ability。
文章浏览阅读846次。本文带大家使用MQTT协议连接华为IoT平台,使用的是E53_IA1 智慧农业扩展板与 BearPi-HM_Nano 开发主板_mqtt 如何对接第三方iot平台
文章浏览阅读567次。HarmonyOS_arkts卡片
文章浏览阅读1k次,点赞19次,收藏20次。ArkTS开发鸿蒙OS连接mongoDB(后端node.js)2024最新教程
文章浏览阅读1.2k次,点赞23次,收藏15次。HarmonyOS与OpenHarmony(1)本质上的不同是:HarmonyOS是鸿蒙操作系统,而OpenHarmony则是从开源项目。这里可以联想一下Android,比如小米手机在Android开源系统的基础上开发了MIUI的手机操作系统,HarmonyOS就类似于MIUI,OpenHarmony类似Android基础底座。(2)HarmonyOS:是双框架,内聚了AOSP(Android Open Source Project )和OpenHarmony等。_鸿蒙模拟器开了怎么跑代码
文章浏览阅读1.1k次,点赞21次,收藏21次。鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之Navigation组件。
文章浏览阅读2k次。由于之前的哥们匆忙离职了,所以鸿蒙手表项目的新版本我临时接过来打包发布,基本上之前没有啥鸿蒙经验,但是一直是做Android开发的,在工作人员的指导下发现打包配置基本上和Android一样,所以这些都不是问题,这里记录一下使用过程中遇到的问题。!过程和遇到的问题基本上都讲解了,关机睡觉,打卡收工。_鸿蒙系统adb命令
文章浏览阅读7.3k次,点赞9次,收藏29次。39. 【多选题】_column和row容器中,设置子组件在主轴方向上的对齐格式
文章浏览阅读1.1k次,点赞13次,收藏24次。18.鸿蒙HarmonyOS App(JAVA)日期选择器-时间选择器点击button按钮显示月份与获取的时间。_harmonyos农历获取