简体   繁体   English

从Android非活动类中的资源读取文本

[英]Reading text from resources in non-activity class in Android

I want to read some text from one of the raw text files in Android application and display a line from this text file in the app. 我想从Android应用程序中的一个原始文本文件中读取一些文本,并在应用程序中显示该文本文件中的一行。 widget. 小部件。

For the MainActivity, I have written a method which get an InputStream using the following code: 对于MainActivity,我编写了一个使用以下代码获取InputStream的方法:

getBaseContext().getResources().openRawResource(R.raw.tips);

My question is how to get reference to Context in the AppwidgetProvider because the MainActivity's onCreate method won't be invoked when user is using the widget and not the app. 我的问题是如何在AppwidgetProvider中获得对Context的引用,因为当用户使用窗口小部件而不是应用程序时,不会调用MainActivity的onCreate方法。 itself. 本身。 The above code results in compiler error in the widgetprovider class. 上面的代码在widgetprovider类中导致编译器错误。

You can get it from onUpdate. 您可以从onUpdate获取它。 pls check the code 请检查代码

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    context.getResources().openRawResource(id);
}

If you have problem with Context only 如果仅上下文有问题

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
      int[] appWidgetIds) {..}

of AppWidgetProvider gets the context object into params.. AppWidgetProvider获取将上下文对象转换为参数。

Can u share your implementation? 你能分享你的实现吗?

The best way to do this is to pass a Context into all of your classes and functions that require to access the application's resources. 最好的方法是将Context传递到需要访问应用程序资源的所有类和函数中。

The second best way to do this is to store a static Context in your Application class. 第二种最佳方法是在您的Application类中存储static Context Here is an example that describes exactly how to do it: Static way to get 'Context' on Android? 这是一个确切描述其操作方法的示例: 在Android上获取“上下文”的静态方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM