Android 如何从主要活动之外读取资产
我需要能够从应用程序的主要活动之外调用 readAsset。我听人们提到需要传递上下文,但语言非常模糊。有人可以描述将调用 readAsset 的功能添加到非主要活动的现有类所需的步骤吗?在主活动中创建一个公共函数并让其他人调用该函数将不起作用,因为我需要添加 readAsset 的地方位于单独的线程中。
I need to be able to be able to call readAsset from outside of the main activity of my application. I have heard people mention needing to pass the Context around, but the language has been very vague. Can someone describe the steps necessary to add the ability to call readAsset to an existing class that is not the main activity? Creating a public function in the main activity and having others call that will not work as the place I need to add readAsset to, is in a separate thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定你在问什么,但也许是这样的?只需添加到现有的类,并使用上下文来检索资产。在您的活动中调用如下方法:
Not sure what you're asking, but perhaps something like this? Just add to the existing class, and use the context to retrieve the assets. In your activity call the method like this:
要读取资源,您需要一个
Context
,但您不必必须使用Activity
作为您的Context
;您可以使用Application
对象代替。Android 上下文不处于活动中?以及其他无活动编程?
您需要将
android:name
属性添加到AndroidManifest.xml 中的
元素首先:现在您可以从任何地方静态调用
MyApplication.getInstance().getAssets()
。或者,您可以使用 Dagger 依赖项注入将
Application
直接注入到你的对象。 (注入Application
上下文有点棘手。请参阅 Dagger 2 注入 Android上下文和在 Danger github 存储库上提交的此问题。)To read assets, you need a
Context
, but you don't have to use anActivity
as yourContext
; you can use theApplication
object instead.Android Context without being in an activity? And other activity-less programming?
You'll need to add the
android:name
attribute to the<application>
element inAndroidManifest.xml
first:Now you can call
MyApplication.getInstance().getAssets()
statically from anywhere.Alternately, you could use Dagger dependency injection to inject an
Application
directly into your object. (Injecting theApplication
context is a bit tricky. See Dagger 2 injecting Android Context and this issue filed on the Danger github repo.)请注意,所有文件系统访问都应在主线程之外完成,因此您不应在 onCreate() 期间读取它们。相反,您应该使用另一个线程,例如 AysncTask 提供的线程。
Note all file system accesses should be done off the main thread, so you shouldn't read them during onCreate(). Instead you should use another thread, such as provided by an AysncTask.