前言
项目工作需要,在游戏APP运行时,获取当前手机的剩余运行内存RAM和ROM。并且要适用于不同的项目,思来想去。最终想到这样的办法,具体的获取的方法在Android工程中实现,然后生成aar ,在Unity中调用。
一、Android工程方法的实现
用AndroidStudio创建一个新项目。创建一个com.pub.mylibrary包名。然后创建一个Unity2Android类。
代码如下(示例):
package com.pub.mylibrary;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.ActivityManager.MemoryInfo;
import android.text.format.Formatter;
public class Unity2Android extends Activity {
//unity项目启动时的上下文
private Activity unityActivity;
private static Context context;
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
}
/**
* 利用反射机制获取unity项目的上下文
* @return
*/
Activity getActivity(){
if (null == unityActivity){
try {
Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
unityActivity = activity;
context = activity;
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (IllegalAccessException e) {
System.out.println(e.getMessage());
} catch (NoSuchFieldException e) {
System.out.println(e.getMessage());
}
}
return unityActivity;
}
/**
* Android调用Unity的方法
* @param gameObjectName 调用的GameObject的名称
* @param functionName 方法名
* @param args 参数
* @return 调用是否成功
*/
boolean CallUnity(String gameObjectName ,String functionName ,String args){
try{
Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
Method method =classtype.getMethod("UnitySendMessage", String.class,String.class,String.class);
method.invoke(classtype,gameObjectName,functionName,args);
return true ;
}catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
System.out.println(e.getMessage());
} catch (IllegalAccessException e) {
System.out.println(e.getMessage());
} catch (InvocationTargetException e) {
}
return false ;
}
/**
Unity调用安卓的方法
* Toast显示unity发送过来的内容
* @param content 消息的内容
* @return 调用是否成功
*/
public boolean ShowToast(String content){
Toast.makeText(getActivity(),content,Toast.LENGTH_SHORT).show();
CallUnity("Main Camera","FromAndroid", "hello unity i'm android");
return true ;
}
public long getAvailMemory(){
unityActivity = getActivity();
ActivityManager am = (ActivityManager)unityActivity.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
// 取得剩余的内存空间
//字符类型转换
long availMem = mi.availMem / (1024 * 1024);
//String availMemStr = formateFileSize(mi.availMem);
//return availMemStr;
return availMem;
}
/**
* 获取android总运行内存大小
*
*/
public long getTotalMemory() {
String str1 = "/proc/meminfo";// 系统内存信息文件
String firstLine = null;
int initial_memory = 0;
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
firstLine = localBufferedReader.readLine().split("\\s+")[1];
localBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (firstLine != null){
initial_memory = (int)Math.ceil((new Float(Float.valueOf(firstLine)/(1024 * 1024 )).doubleValue()));
}
return initial_memory * 1024 ;
}
private String formateFileSize(long size){
unityActivity = getActivity();
return Formatter.formatFileSize(unityActivity, size);
}
public long appSize(){
Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memoryInfo);
long total = memoryInfo.getTotalPss() / 1024;
return total;
}
}
二、生成aar
在AndroidStudio中Build下的Make Module 。然后在build 下的outputs 下的aar中找到对应生成的aar。
三、Untiy中的调用
把第二步骤生成的aar文件复制到Unity目录下Plugins中下的Android文件夹下。Unity中调用方法为文章来源:https://www.toymoban.com/news/detail-574988.html
AndroidJavaObject _ajc;
[DllImport("__Internal")]
public static extern int _showTest();
void Start()
{
_ajc = new AndroidJavaObject("com.pub.mylibrary.Unity2Android");
}
/// <summary>
/// 当前设备的RAM
/// </summary>
/// <returns></returns>
private float getTotalMemory()
{
long totalMemory = 0;
#if UNITY_ANDROID
try
{
totalMemory = _ajc.Call<long>("getTotalMemory");
}
catch (System.Exception e)
{
totalMemory = 0;
throw;
}
#elif UNITY_IOS
totalMemory = 0;
#endif
return totalMemory;
}
/// <summary>
/// 当前设备剩余的RAM
/// </summary>
/// <returns></returns>
private float getAvailMemory()
{
long availMemory = 0;
#if UNITY_ANDROID
try
{
availMemory = _ajc.Call<long>("getAvailMemory");
}
catch (System.Exception e)
{
availMemory = 0;
throw;
}
#elif UNITY_IOS
//try
//{
// availMemory = (long)availableMemory();
//}
//catch (System.Exception e)
//{
// availMemory = 0;
// throw;
//}
#endif
return availMemory;
}
/// <summary>
/// 当前APP占用的的RAM
/// </summary>
/// <returns></returns>
private float getAppOccupyMemory()
{
long appOccupyMemory = 0;
#if UNITY_ANDROID
try
{
appOccupyMemory = _ajc.Call<long>("appSize");
}
catch (System.Exception e)
{
appOccupyMemory = 0;
throw;
}
#elif UNITY_IOS
//try
//{
// appOccupyMemory = (long)usedMemory();
//}
//catch (System.Exception e)
//{
// appOccupyMemory = 0;
// throw;
//}
#endif
return appOccupyMemory;
}
以上就是实现的大致过程,仅仅做个记录,怕忘记怎么实现。文章来源地址https://www.toymoban.com/news/detail-574988.html
到了这里,关于Unity获取Android手机的RAM和剩余RAM和ROM的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!