Unity streamingAssetsPath 读取文件

// http://docs.unity3d.com/ScriptReference/WWW.html
// https://zhuanlan.zhihu.com/p/38090723
// https://stackoverflow.com/questions/35582074/access-unity-streamingassets-on-android
// https://forum.unity.com/threads/finding-all-files-in-streamingassets.255000/
// https://answers.unity.com/questions/210909/android-streamingassets-file-access.html
// https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html?_ga=2.7980081.2029905823.1576401196-1224155099.1572446551
// https://docs.unity3d.com/Manual/StreamingAssets.html

 

=======================

https://answers.unity.com/questions/210909/android-streamingassets-file-access.html

I may be a little late to the party, but it I managed to do it without WWW, @mpavlinsky.

Streaming Assets remain uncompressed in APK/OBB archive, so they can be read directly - if you know their offset and size. And once you do such approach is ~10 times faster (on my device at least), does not suffer memory duplication issue (WWW does) and can be used synchronously (not in a coroutine) and in any thread.

Long story short, I created Better Streaming Assets plugin that does exactly that, comes for free and is open source.

Asset Store: https://www.assetstore.unity3d.com/#!/content/103788

Github: https://github.com/gwiazdorrr/BetterStreamingAssets

Some lovely snippets:

 

https://docs.unity3d.com/Manual/StreamingAssets.html

  • Most platforms (Unity Editor, Windows, Linux players, PS4, Xbox One, Switch) use Application.dataPath + "/StreamingAssets",
  • macOS player uses Application.dataPath + "/Resources/Data/StreamingAssets",
  • iOS uses Application.dataPath + "/Raw",
  • Android uses files inside a compressed APK
    /JAR file, "jar:file://" + Application.dataPath + "!/assets".

Android 直接读取 jar 文件

 

====================

https://blog.csdn.net/ShareUs/article/details/86180943

-- assets下的文件,安装assets下的APK文件

Android 系统为每个新设计的程序提供了/assets目录,这个目录保存的文件可以打包在程序里。/res 和/assets的不同点是,android不为/assets下的文件生成ID。如果使用/assets下的文件,需要指定文件的路径和文件名(是全名)。
 assets下APK文件问题:assets目录下的文件只能得到输入输出流,所以是不是可以把它再输出到一个新的文件里,然后调用Android程序进行安装?

Android安装assets下的APK文件- http://blog.sina.com.cn/s/blog_628cc2b70101dwk6.html
Android安装assets下的APK文件:
(1)先把assets中的APK文件copy到内置SD卡中,比如/mnt/sdcard
(2)然后通过mContext.startActivity(intent);启动一个APK
(3)这个APK的启动是带提示框的,不能被静默安装

-- 动态加载技术?
动态加载技术就是使用类加载器加载相应的apk、dex、jar(必须含有dex文件),再通过反射获得该apk、dex、jar内部的资源(class、图片、color等等)进而供宿主app使用。

  - 动态加载apk有两种方式:
 一种是将资源主题包的apk安装到手机上再读取apk内的资源,这种方式的原理是将宿主app和插件app设置相同的sharedUserId,这样两个app将会在同一个进程中运行,并可以相互访问内部资源了。新建工程Skin-Plugin,将要更换的图片或者xml文件放在对应的drawable文件夹内,在AndroidManifest.xml中增加shareUserId,然后打包成apk文件。如果是不需要安装apk的,就不用设置shareUserId了。
 一种是不用安装资源apk的方式。其原理是通过DexClassLoader类加载器去加载指定路径下的apk、dex或者jar文件,反射出R类中相应的内部类然后根据资源名来获取我们需要的资源id,然后根据资源id得到对应的图片或者xml文件。

android 插件化动态加载apk包(插件apk不需要安装)- https://blog.csdn.net/u012898654/article/details/80341403

-- 加载插件APK里面的资源
Android如何加载插件APK里面的资源- https://blog.csdn.net/liangdong520/article/details/76149148
Android如何加载插件APK里面的资源 ??

如果想要做到插件化,需要了解Android资源文件的打包过程,这样可以为每一个插件进行编号,然后按照规则生成R文件。动态加载插件apk中的资源- https://www.jianshu.com/p/c2532d69a08a

 

=====================

Unity Android assets

 

===================

其中的am对象为AssetManager实例,通过Activity.getAssets()获得,用来访问assets目录资源

https://my.oschina.net/u/614511/blog/76957

 

==================

Android – Read file from Assets

http://www.technotalkative.com/android-read-file-from-assets/

Android – Read file from Assets

By Paresh Mayani - November, 19th 2011

Problem: How to read files (Images or text files) from Assets folder?

Description:

I assume you are aware about File reading operation, but here we have question that how can we get a list of files which we have placed in Assets folder. Here AssetManager class can help you to access any files lying inside the Assets directory of android application ( (or any sub-folders inside the Assets directory).

For accessing files from Assets directory, you require object of the AssetManager class, which you can create by using getAssets() method:

1

AssetManager assetManager = getAssets();

Now, you can get the files by using list(String Path) method of AssetManager class:

1

2

String[] files = assetManager.list("");  // files from 'assets' directory

String[] files = assetManager.list("Files"); // files from 'assets/Files' directory

And go through example for the rest of the procedure. In the example, you can find code for fetching files name and displaying it, reading text file, open image file and creating drawable from it and displaying the same in ImageView.

Output:

 

 

Solution:

ReadFileAssetsActivity.java

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

package com.paresh.readfileasset;

 

import java.io.IOException;

import java.io.InputStream;

 

import android.app.Activity;

import android.content.res.AssetManager;

import android.graphics.drawable.Drawable;

import android.os.Bundle;

import android.widget.ImageView;

import android.widget.TextView;

 

/**

 * @author Paresh N. Mayani

 * @Website http://www.technotalkative.com

 */

public class ReadFileAssetsActivity extends Activity {

 

    /** Called when the activity is first created. */

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

 

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

 

        TextView txtContent = (TextView) findViewById(R.id.txtContent);

        TextView txtFileName = (TextView) findViewById(R.id.txtFileName);

        ImageView imgAssets = (ImageView) findViewById(R.id.imgAssets);

 

        AssetManager assetManager = getAssets();

 

        // To get names of all files inside the "Files" folder

        try {

            String[] files = assetManager.list("Files");

 

            for(int i=0; i<files.length; i++)            {               txtFileName.append("\n File :"+i+" Name => "+files[i]);

            }

        } catch (IOException e1) {

            // TODO Auto-generated catch block

            e1.printStackTrace();

        }

 

        // To load text file

        InputStream input;

        try {

            input = assetManager.open("helloworld.txt");

 

             int size = input.available();

             byte[] buffer = new byte[size];

             input.read(buffer);

             input.close();

 

             // byte buffer into a string

             String text = new String(buffer);

 

             txtContent.setText(text);

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

 

        // To load image

        try {

            // get input stream

            InputStream ims = assetManager.open("android_logo_small.jpg");

 

            // create drawable from stream

            Drawable d = Drawable.createFromStream(ims, null);

 

            // set the drawable to imageview

            imgAssets.setImageDrawable(d);

        }

        catch(IOException ex) {

            return;

        }

    }

}

main.xml

01

02

03

04

05

06

07

08

09

10

11

12

<?xml version="1.0" encoding="utf-8"?>

 

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">

    <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">

    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:id="@+id/txtContent">

 

    <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/imgAssets">

 

     <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txtFileName">

</TextView></ImageView></TextView></LinearLayout>

 

</Scrollview>

Download example: https://github.com/PareshMayani/Android-ReadFileAssets

 

 

=============================

android file open

https://answers.unity.com/questions/205212/android-file-open.html

android file open

I develop android app. I want to open my text file in plugin, but it can not open file. My code is following,

// plugin side void openTextTest(char* filename, jobject asset_manager){

 
  1. AAssetManager* mgr = AAssetManager_fromJava(env, asset_manager);
  2. if(mgr!=NULL){
  3.  
  4. AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_UNKNOWN);
  5. if(asset!=NULL){ // AAssetManager_open() return NULL. Why?
  6. ...
  7. AAsset_close(asset);
  8. }
  9. }

}

// cs script side void OnGUI(){

 
  1. string setting_path = Application.persistentDataPath + "/assets/sample.txt";
  2.  
  3. IntPtr cls_Activity = (IntPtr)AndroidJNI.FindClass("com/unity3d/player/UnityPlayer");
  4. IntPtr fid_Activity = AndroidJNI.GetStaticFieldID(cls_Activity, "currentActivity", "Landroid/app/Activity;");
  5. IntPtr obj_Activity = AndroidJNI.GetStaticObjectField(cls_Activity, fid_Activity);
  6.  
  7. IntPtr obj_cls = AndroidJNI.GetObjectClass(obj_Activity);
  8. IntPtr asset_func = AndroidJNI.GetMethodID(obj_cls, "getAssets", "()Landroid/content/res/AssetManager;");
  9. jvalue[] asset_array = new jvalue[2]; // <- ?
  10. IntPtr assetManager = AndroidJNI.CallObjectMethod(obj_Activity, asset_func, asset_array);
  11. if(assetManager!=null){
  12. openTextTest(setting_path, assetManager);
  13. }

}

Where is wrong?

评论 · Show 1

2条回复

· 添加您的回复

  • 排序: 
  •  
  •  
  •  

 

0

个解答,截止shintaro · 2012年01月17日 03:11

I wrote. I checked as follows.

 

 
  1. //plugin side
  2. jstring openTextTest(char* filename, jobject asset_manager){
  3. AAssetManager* mgr = AAssetManager_fromJava(env, asset_manager);
  4. if(mgr!=NULL){
  5. AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_UNKNOWN);
  6. if(asset!=NULL){ // AAssetManager_open() return NULL. Why?
  7. ...
  8. AAsset_close(asset);
  9. return env->NewStringUTF("success!");
  10. }
  11. return env->NewStringUTF("asset open failure!");
  12. }
  13. return env->NewStringUTF("failure!");
  14. }

 

As a result, this return "asset open failure!".

评论 · 分享

avatar image

0

个解答,截止shintaro · 2012年01月17日 09:37

Sorry, i solved by setting a path as follows. Thank you.

 
  1. string setting_path = "sample.txt";

=======================

https://forum.unity.com/threads/why-the-asset-bundle-slow-in-streamingassets-on-android-device.401234/

Why the asset bundle slow in StreamingAssets on android device?

 

==========================

Unity Android assets  AssetManager

=================

Home  >  Android

Android AssetManager Example to Load Image from assets Folder

https://www.concretepage.com/android/android-assetmanager-example-to-load-image-from-assets-folder

 

This page will cover Android AssetManager example to load image from assets folder. We keep text, images, videos, pdf etc in assets directory. android.content.res.AssetManager is used to access raw asset from /assets folder. Using this API, we can open the asset for the given asset path and can list all assets for the given folder path. We can instantiate AssetManager in our Activity as follows.

AssetManager assetManager = getAssets();
 

AssetManager.open()

It opens an asset for the given path. Suppose we need to open an image kept in /assets/img/image1.png, the path will be used as img/image1.png. Find the code snippet.

InputStream is = assetManager.open("img/image1.png");
Bitmap  bitmap = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bitmap);  

AssetManager.open() returns InputStream that is used with BitmapFactory.decodeStream() that returns Bitmap which is used with imageView.setImageBitmap().

 

AssetManager.list()

To list all the assets for the given folder within /assets folder, we use AssetManager.list(). Suppose we have some files within /assets/img and we need to list all those files, then we write code as follows.

String[] imgPath = assetManager.list("img");
 

Here we get String array of file names within img directory.

Complete Example

Find the project structure in eclipse.

 

Now find the Activity class and XML files used in the example.
MainActivity.java

package com.concretepage;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
	private final static String TAG = "MainActivity"; 
	private ImageView imageView;
	private ImageView imageViewbyCode;
	private LinearLayout myLayout;
	private AssetManager assetManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView)findViewById(R.id.image);
		myLayout = (LinearLayout)findViewById(R.id.myLayout);
   	        assetManager = getAssets();
	}
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
               getMenuInflater().inflate(R.menu.menu_main, menu);
               return true;
        }
        public void displayOneImage(View v) {
  	    if (imageViewbyCode != null) {
  		    imageViewbyCode.setVisibility(View.GONE);
  	    }
  	    imageView.setVisibility(View.VISIBLE);
            try {
			InputStream is = assetManager.open("img/image1.png");
			Bitmap  bitmap = BitmapFactory.decodeStream(is);
			imageView.setImageBitmap(bitmap);
	    } catch (IOException e) {
			Log.e(TAG, e.getMessage());
	    }
        }
        public void listAllImages(View v) {
  	    if (imageView != null) {
  	    	imageView.setVisibility(View.GONE);
  	    }
    	    try {
			String[] imgPath = assetManager.list("img");
			for (int i = 0; i< imgPath.length; i++) {
				InputStream is = assetManager.open("img/"+imgPath[i]);
				Log.d(TAG, imgPath[i]);
				Bitmap  bitmap = BitmapFactory.decodeStream(is);
				
				imageViewbyCode = new ImageView(this);
				imageViewbyCode.setImageBitmap(bitmap);
        	                LinearLayout.LayoutParams params =  new LinearLayout
    			            .LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        	                imageViewbyCode.setLayoutParams(params);        
    	                        myLayout.addView(imageViewbyCode);
			}
	     } catch (IOException e) {
			Log.e(TAG, e.getMessage());
	     }
    }
} 


res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    
    tools:context=".MainActivity"
    android:id="@+id/myLayout">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnmsg1"
        android:onClick="displayOneImage"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnmsg2"
        android:onClick="listAllImages"/>
    <ImageView
	android:id="@+id/image"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="#000000"
	android:gravity="center"
	android:padding="32dp"
	android:contentDescription="@string/imgDesc"/>  
</LinearLayout> 	 

Output

1. On click of Display Single Image.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值