标签 Android 下的文章

目前有截图、点击的功能,其他只有测试(划屏,装软件,输入中文)代码,需要修改

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class Main : MonoBehaviour
{
    private string adbPath;
    private string filePath;
    /// <summary>
    /// 列出设备按钮
    /// </summary>
    public Button btnList;

    public Transform togglePrefab;

    /// <summary>
    /// 所有设备
    /// </summary>
    Dictionary<string, GameObject> advs = new Dictionary<string, GameObject>();
    /// <summary>
    /// 选中的设备
    /// </summary>
    public List<string> sdvs = new List<string>();

    public InputField inputFieldX;
    public InputField inputFieldY;
    /// <summary>
    /// 点击指定位置按钮
    /// </summary>
    public Button btnClick;
    public Image screenImage;
    public Button btnCapture;
    public Button getCapture;

    private void Awake()
    {
        Loom.Initialize();
    }

    // Use this for initialization
    void Start()
    {
        adbPath = @Application.streamingAssetsPath + "/adb.exe";
        filePath = @Application.streamingAssetsPath;
        btnList.onClick.AddListener(ClickList);
        togglePrefab.gameObject.SetActive(false);
        btnClick.onClick.AddListener(ClickPose);
        btnCapture.onClick.AddListener(Capture);
    }

    string StartProcess(string args, Action action)
    {
        Process process = new Process();
        process.StartInfo.FileName = adbPath;
        process.StartInfo.Arguments = args;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
        process.Start();
        process.WaitForExit();
        if (action != null)
        {
            action();
        }
        return process.StandardOutput.ReadToEnd();
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnGUI()
    {
        //if (GUI.Button(new Rect(0, 0, 200, 50), "列出设备"))
        //{
        //    string args = "devices";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 50, 200, 50), "点击"))
        //{
        //    string args = "-s de81f1c shell input tap 400 400";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 100, 200, 50), "手机截屏"))
        //{
        //    string args = "-s de81f1c shell screencap -p /sdcard/screenshot.jpg";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 150, 200, 50), "获取截屏"))
        //{
        //    string args = "-s de81f1c pull /sdcard/screenshot.jpg " + @Application.streamingAssetsPath + "/screenshot.jpg";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 200, 200, 50), "划屏"))
        //{
        //    string args = "-s de81f1c shell input swipe 800 300 200 300";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 250, 200, 50), "安装ADB键盘"))
        //{
        //    string args = "-s 127.0.0.1:62001 install " + Application.streamingAssetsPath + "/ADBKeyboard.apk";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 300, 200, 50), "设置ADB默认键盘"))
        //{
        //    string args = "-s 127.0.0.1:62001 shell ime set com.android.adbkeyboard/.AdbIME";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}
        //if (GUI.Button(new Rect(500, 350, 200, 50), "输入文字"))
        //{
        //    string args = "-s 127.0.0.1:62001 shell am broadcast -a ADB_INPUT_TEXT --es msg '曹尼玛终于出中文了!'";
        //    UnityEngine.Debug.Log(StartProcess(args));
        //}

    }

    void ClickList()
    {
        string args = "devices";
        string opt = StartProcess(args, null);
        List<string> list = opt.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
        list = list.Where(s => !string.IsNullOrEmpty(s)).ToList();
        if (list.Count < 2)
        {
            return;
        }
        for (int i = 1; i < list.Count; i++)
        {
            string[] dns = list[i].Split('\t');
            string id = dns[0];
            string name = dns[1];
            if (advs.ContainsKey(id))
            {
                continue;
            }
            Transform item = CreateItem(togglePrefab);
            item.Find("Label").GetComponent<Text>().text = "设备ID:" + id + "  设备名:" + name;
            item.name = dns[0];
            item.GetComponent<Toggle>().onValueChanged.AddListener(state => { ToggleClick(state, item); });
            item.gameObject.SetActive(true);
            advs.Add(id, item.gameObject);
        }
        UnityEngine.Debug.Log(opt);
    }

    void ToggleClick(bool state, Transform go)
    {
        if (state)
        {
            sdvs.Add(go.name);
        }
        else
        {
            sdvs.Remove(go.name);
        }
    }

    /// <summary>
    /// 点击
    /// </summary>
    void ClickPose()
    {
        for (int i = 0; i < sdvs.Count; i++)
        {
            string args = "-s " + sdvs[i] + " shell input tap " + inputFieldX.text + " " + inputFieldY.text;
            Loom.RunAsync(() =>
            {
                string opt = StartProcess(args, Capture);
                UnityEngine.Debug.Log(opt);
            });
        }
    }

    /// <summary>
    /// 截图
    /// </summary>
    void Capture()
    {
        for (int i = 0; i < sdvs.Count; i++)
        {
            string args = "-s " + sdvs[i] + " shell screencap -p /sdcard/screenshot.jpg";
            Loom.RunAsync(() =>
            {
                string opt = StartProcess(args, GetCapture);
                UnityEngine.Debug.Log(opt);
            });
        }
    }

    /// <summary>
    /// 获取截图
    /// </summary>
    void GetCapture()
    {
        for (int i = 0; i < sdvs.Count; i++)
        {
            string args = "-s " + sdvs[i] + " pull /sdcard/screenshot.jpg " + filePath + "/screenshot.jpg";
            Loom.RunAsync(() =>
            {
                string opt = StartProcess(args, ShowCapture);
                UnityEngine.Debug.Log(opt);
            });
        }
    }

    /// <summary>
    /// 显示截图
    /// </summary>
    void ShowCapture()
    {
        Loom.QueueOnMainThread(() =>
        {
            StartCoroutine(LoadImg());
        });
    }

    /// <summary>
    /// 加载图片
    /// </summary>
    /// <returns></returns>
    IEnumerator LoadImg()
    {
        WWW www = new WWW("file:///" + filePath + "/screenshot.jpg");
        yield return www;
        Sprite sprite = Sprite.Create(www.texture,new Rect(0, 0, www.texture.width, www.texture.height), Vector2.zero);
        screenImage.sprite = sprite;
        www.Dispose();
        www = null;
    }

    private Transform CreateItem(Transform prefab)
    {
        Transform item = Instantiate(prefab);
        item.SetParent(prefab.parent);
        item.localPosition = Vector3.zero;
        item.localScale = new Vector3(1, 1, 1);
        return item;
    }

    private void OnApplicationQuit()
    {

    }
}

TIM截图20190321164754.jpg

工程地址https://gitee.com/awnuxcvbn/GroupControl

1、安卓端代码

package cn.net.xuefei.schemedemo;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
 
public class MainActivity extends UnityPlayerActivity {

    private String launchInfo="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launchInfo = onLaunchInfo();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        launchInfo = onLaunchInfo();
    }

    private String onLaunchInfo()
    {
        String info="";
        Uri uri = getIntent().getData();
        if (uri != null) {
            // 完整的url信息
            String url = uri.toString();

            info = url;
            Log.e("Unity", "url: " + url);
        }
        return info;

    }

    public void getLaunchInfo()
    {
        UnityPlayer.UnitySendMessage("Main Camera", "OnLaunchInfo", launchInfo);
        launchInfo="";
    }
}

2、Unity中 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package = "cn.net.xuefei.schemedemo"
    android:versionCode="1"
    android:versionName="1.0">

  <application
      android:allowBackup="true"
      android:icon="@drawable/app_icon"
      android:label="@string/app_name"
      android:supportsRtl="true">

    <activity android:name=".MainActivity" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="scheme"
              android:host="host"
              android:path="/path"
              android:port="8888"/>
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
  </application> 
</manifest>

3、Unity中代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

#if UNITY_IOS
using System.Runtime.InteropServices;
#endif

public class SchemeDemo : MonoBehaviour
{
    public Text text;

    // Use this for initialization
    void Start()
    {
        GetInfo();
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void OnLaunchInfo(string launchInfo)
    {
        Debug.LogError("launchInfo:" + launchInfo);
        text.text = launchInfo;
    }

    public void GetInfo()
    {
        
#if UNITY_ANDROID
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("getLaunchInfo");
#elif UNITY_IOS
        _GetLaunchInfo();
#endif
    }

    private void OnApplicationFocus(bool focus)
    {
        Debug.LogError("focus:" + focus);
        if (true)
        {
            GetInfo();
        }
    }

#if UNITY_IOS
    [DllImport("__Internal")]
    private static extern void _GetLaunchInfo();
#endif
}

4、设置Unity iOS URL Schemes,修改导出的Xcode工程中的UnityAppController.mm

#import "UnityAppController.h"

NSString *URLString = @"";

// 向Unity传递参数;
extern void UnitySendMessage(const char *, const char *, const char *);

//添加的代码
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    URLString = [url absoluteString]; 
    return YES;
}

- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    //添加的代码
    URLString = [url absoluteString]; 
    return YES;
}

extern "C"  
{  
    void _GetLaunchInfo();  
}  
  
void _GetLaunchInfo()  
{    
    UnitySendMessage( "Main Camera", [@"OnLaunchInfo" UTF8String], [URLString UTF8String] );  
    // 清空,防止造成干扰;  
    URLString = @"";  
}  

5、网页

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input  id="btn" type="button" value="唤起SchemeDemo">
    <script>
        var btn = document.getElementById('btn');
        
        btn.onclick = function () {
            jump('scheme://host:8888/path?ps=123456');
        };
        
        function  GetMobelType()  {                
            var  browser  =   {                    
                versions:   function()  {                        
                    var  u  =  window.navigator.userAgent;    
                    console.log(u);  //Safari浏览器 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.1 Safari/605.1.15                  
                    return  {                            
                        trident:  u.indexOf('Trident')  >  -1, //IE内核
                        presto:  u.indexOf('Presto')  >  -1, //opera内核
                        Alipay:  u.indexOf('Alipay')  >  -1, //支付宝
                        webKit:  u.indexOf('AppleWebKit')  >  -1, //苹果、谷歌内核
                        gecko:  u.indexOf('Gecko')  >  -1  &&  u.indexOf('KHTML')  ==  -1, //火狐内核
                        mobile:  !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                        ios:  !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                        android:  u.indexOf('Android')  >  -1  ||  u.indexOf('Linux')  >  -1, //android终端或者uc浏览器
                        iPhone:  u.indexOf('iPhone')  >  -1  ||  u.indexOf('Mac')  >  -1, //是否为iPhone或者安卓QQ浏览器
                        //iPhone: u.match(/iphone|ipod|ipad/),//
                        iPad:  u.indexOf('iPad')  >  -1, //是否为iPad
                        webApp:  u.indexOf('Safari')  ==  -1, //是否为web应用程序,没有头部与底部
                        weixin:  u.indexOf('MicroMessenger')  >  -1, //是否为微信浏览器
                        qq: u.match(/\sQQ/i) !== null, //是否QQ
                        Safari:  u.indexOf('Safari')  >  -1,
                          ///Safari浏览器,
                    };                    
                }()                
            };                
            return  browser.versions;            
        }
        
        
        function jump(myurl) { 
            var timeout = 2300, timer = null;
            if(GetMobelType().weixin) {
                // 微信浏览器不支持跳转
                // 可以显示提示在其他浏览器打开
            } else {
                var startTime = Date.now();
                if(GetMobelType().android) {
                    var ifr = document.createElement('iframe');
                    ifr.src = myurl;//这里是唤起App的协议,有Android可爱的同事提供
                    ifr.style.display = 'none';
                    document.body.appendChild(ifr);
                    timer = setTimeout(function() {
                        var endTime = Date.now();
                        if(!startTime || endTime - startTime < timeout + 300) {
                            document.body.removeChild(ifr);
                            //window.open("唤起失败跳转的链接");
                            window.open("https://www.ganghood.net.cn/SchemeDemo.apk");
                        }
                    }, timeout);
                }
                if(GetMobelType().ios || GetMobelType().iPhone || GetMobelType().iPad) {
                    if(GetMobelType.qq) { 
                    // ios的苹果浏览器
                    // 提示在浏览器打开的蒙板
                    } else {
                        /*var ifr = document.createElement("iframe");
                        ifr.src = myurl;
                        ifr.style.display = "none";*/ // iOS9+不支持iframe唤起app
                        window.location.href = myurl; //唤起协议,由iOS小哥哥提供
                        //document.body.appendChild(ifr);
                        
                        timer = setTimeout(function() {
                            // window.location.href = "ios下载的链接";
                            window.location.href = "https://www.ganghood.net.cn/没有该文件.ipa";
                        }, timeout);
                    };
                }
            }
        }
    </script>
</body>
</html>

TIM图片20190315140409.jpg

工程地址https://gitee.com/awnuxcvbn/SchemeDemo

task makeJar(type: Copy) {
    //删除存在的
    delete 'build/libs/plugin.jar'
    //设置拷贝的文件
    from('build/intermediates/packaged-classes/release/')
    //打进jar包后的文件目录
    into('build/libs/')
    //将classes.jar放入build/libs/目录下
    //include ,exclude参数来设置过滤
    //(我们只关心classes.jar这个文件)
    include('classes.jar')
    //重命名
    rename('classes.jar', 'plugin.jar')
}
makeJar.dependsOn(build)

Termina 输入命令 gradlew makeJar 打包jar

Android代码

package cn.net.xuefei.unityrec; 
import java.io.File;
import java.io.IOException;
import com.unity3d.player.UnityPlayerActivity;
import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.widget.Toast;
 
public class MainActivity extends UnityPlayerActivity {
        private static final int RECORD_REQUEST_CODE = 101;
        private static final int STORAGE_REQUEST_CODE = 102;
        private static final int AUDIO_REQUEST_CODE = 103;
        private static final int SHOW = 1;
        private static final int CANCEL = 2;
        private boolean isRecording;
        public static Context currentActivity;
        private MediaProjectionManager mediaProjectionManager;
        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                        case SHOW:
                                if (isRecording) {
                                        Toast.makeText(MainActivity.this, "录制已开始", Toast.LENGTH_SHORT).show();
                                } else {
                                        startScreenCapture();
                                        isRecording = true;
                                }
                                break;
                        case CANCEL:
                                if (isRecording) {
                                        mediaRecorder.stop();
                                        mediaRecorder.reset();
                                        mediaProjection.stop();
                                        virtualDisplay.release();
                                        isRecording = false;
                                        insertVideoToMediaStore(getSaveDirectory() + videoName);
                                        Toast.makeText(MainActivity.this, "录制结束", Toast.LENGTH_SHORT).show();
                                } else {
                                        Toast.makeText(MainActivity.this, "没有开始录制", Toast.LENGTH_SHORT).show();
                                }
                                break;
                        }
                }
        };
        private MediaProjection mediaProjection;
        private MediaRecorder mediaRecorder;
        private VirtualDisplay virtualDisplay;
        /**
         * 屏幕的宽度
         */
        private int screenWidth;
        /**
         * 屏幕的高度
         */
        private int screenHeight;
        /**
         * 屏幕的像素
         */
        private int screenDpi;
        private DisplayMetrics metrics;
        /**
         * 保存在相册视频的名字
         */
        private String videoName;
 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                mediaRecorder = new MediaRecorder();
                metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                /**
                 * 动态注册权限
                 */
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        STORAGE_REQUEST_CODE);
                }
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                                Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.RECORD_AUDIO },
                                        AUDIO_REQUEST_CODE);
                }
                currentActivity = this;
                //mUnityPlayer.requestFocus();
        }
 
        /**
         * unity调用的方法,需要用一个handler进行处理实现功能,直接无法实现。
         */
        public void stopRecordin() {
                mHandler.sendEmptyMessage(CANCEL);
        }
 
        /**
         * unity调用的方法,需要用一个handler进行处理实现功能,直接无法实现。
         */
        public void startRecording() {
                mHandler.sendEmptyMessage(SHOW);
 
        }
 
        private void startScreenCapture() {
                mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
                Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
                startActivityForResult(captureIntent, RECORD_REQUEST_CODE);
        }
 
        public void setConfig(int screenWidth, int screenHeight, int screenDpi) {
                this.screenWidth = screenWidth;
                this.screenHeight = screenHeight;
                this.screenDpi = screenDpi;
        }
 
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
                        mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
                        setConfig(metrics.widthPixels, metrics.heightPixels, metrics.densityDpi);
                        startRecord();
                        Toast.makeText(this, "开始录制", Toast.LENGTH_SHORT).show();
                }
        }
 
        public boolean startRecord() {
                initRecorder();
                createVirtualDisplay();
                mediaRecorder.start();
                return true;
        }
 
        private void createVirtualDisplay() {
                virtualDisplay = mediaProjection.createVirtualDisplay("MainScreen", screenWidth, screenHeight, screenDpi,
                                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
        }
 
        private void initRecorder() {
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                videoName = System.currentTimeMillis() + ".mp4";
                mediaRecorder.setOutputFile(getSaveDirectory() + videoName);
                mediaRecorder.setVideoSize(screenWidth, screenHeight);
                mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
                mediaRecorder.setVideoFrameRate(30);
                try {
                        mediaRecorder.prepare();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
 
        public String getSaveDirectory() {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        String screenRecordPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
                                        + "DCIM" + File.separator + "Camera" + File.separator;
                        return screenRecordPath;
                } else {
                        return null;
                }
        }
 
        public void insertVideoToMediaStore(String filePath) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, filePath);
                // video/*
                values.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
                getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        }
 
        /**
         * 打开相册,
         *
         * @return
         */
        public void openAlbum() {
                Intent intent = new Intent(Intent.ACTION_PICK);
                startActivity(intent);
        }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.net.xuefei.unityrec"
    android:versionCode="1"
    android:versionName="1.0" >
 
  <uses-sdk
      android:minSdkVersion="22"
      android:targetSdkVersion="22" />
  
  <uses-permission android:name="android.permission.RECORD_AUDIO" />
  <!--往sdcard中写入数据的权限 -->
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  <!--在sdcard中创建/删除文件的权限 -->
  <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
 
  <application
       >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
 
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
 
</manifest>

Unity代码

using UnityEngine;
using System.Collections;
 
public class UnityRec : MonoBehaviour
{ 
    // Use this for initialization
    void Start()
    {
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
 
    void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 300, 300), "开始录屏"))
        {
#if UNITY_ANDROID
            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            jo.Call("startRecording");
#elif UNITY_IPHONE
           
#endif
        }
 
        if (GUI.Button(new Rect(0, 300, 300, 300), "停止录屏"))
        {
# if UNITY_ANDROID
            AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            jo.Call("stopRecordin");
#elif UNITY_IPHONE
 
#endif
        }
    }
}

1.jpg
2.jpg
3.jpg

package com.xuefei.game;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.unity3d.player.UnityPlayerNativeActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
 
public class MainActivity extends UnityPlayerNativeActivity {
    public static Context context;
    public static MainActivity mainActivity;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
 
        super.onCreate(savedInstanceState);
        mainActivity = this;
    }
 
    // 保存到相册
    public static void savePng(final String fileName) {
 
        context = mainActivity.getApplicationContext();
 
        mainActivity.runOnUiThread(new Runnable() {
            public void run() {
 
                Bitmap bitmap = BitmapFactory.decodeFile(Environment
                        .getExternalStorageDirectory()
                        + "/Android/data/com.xuefei.game/files/"
                        + fileName
                        + ".png");
 
                File file = new File(Environment.getExternalStorageDirectory()
                        + "/DCIM/Camera", fileName + ".jpg");
 
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    Log.w("cat", e.toString());
                }
                bitmap.compress(CompressFormat.JPEG, 100, fos);
 
                try {
                    fos.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.w("cat", e.toString());
                }
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.w("cat", e.toString());
                }
                bitmap.recycle();//扫描保存的图片
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" +Environment.getExternalStorageDirectory()
                        + "/DCIM/Camera/"+fileName + ".jpg")));
                 
                Toast.makeText(context, "照片已保存到相册", Toast.LENGTH_SHORT).show();
  
            }
        });
    }
}

Unity中代码:

        if (GUI.Button(new Rect(0, 720, 400, 120), "SavePng"))
        {
            StartCoroutine(SavePngToSD(DateTime.Now.ToFileTime().ToString()));
        }
 
    /// <summary>
    /// 截图后先检测图片是否保存成功然后调用保存到相册
    /// </summary>
    /// <param name="name"></param>
    public void SavePng(string name)
    {
#if UNITY_ANDROID
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.CallStatic("SavePng", name);
#elif  UNITY_IPHONE
 
#endif
    }
 
/// <summary>
    /// 保存截图到相册
    /// </summary>
    /// <param name="pngName"></param>
    /// <returns></returns>
    IEnumerator SavePngToSD(string pngName)
    {
        yield return new WaitForEndOfFrame();
        Application.CaptureScreenshot(pngName + ".png");
        while (!IsFileExistByPath(Application.persistentDataPath + "/" + pngName + ".png"))
        {
            yield return new WaitForSeconds(0.05f);
        }
        SavePng(pngName);
        yield return new WaitForSeconds(0.3f);
        //测试请求文件
        WWW www = new WWW("file:///" + Application.persistentDataPath + "/" + pngName + ".png");
 
        yield return www;
    }
 
    /// <summary>
    /// 检测文件是否存在
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static bool IsFileExistByPath(string path)
    {
        FileInfo info = new FileInfo(path);
        bool b = false;
        if (info == null || info.Exists == false)
        {
            b = false;
        }
        else
        {
            b = true;
        }
        return b;
    }

注意文件路径是否存在,不存在就创建

流程:Unity截屏--调用安卓拷贝到相册--扫描保存的文件

解决的问题:截屏图片在相册不显示。

1.png
2.png