无法在 BroadcastReceiver 中使用 openFileInput

Unable to use openFileInput in a BroadcastReceiver

我是编码的新手,我正在尝试自己学习它,但我 运行 遇到了我正在开发的应用程序中无法在广播接收器中使用 openFileInput 的问题。这是代码:

public class AlarmReceiver 扩展 BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {



}

//阅读结束

DateFormat format = DateFormat.getDateInstance();

TextView text;
Button btn;

DateFormat formate = DateFormat.getTimeInstance();
Calendar calender2 = Calendar.getInstance();
TextView txt2;
Button btn2;

//从头开始阅读

private String readFromFilename() {

    String ret = "";

    try {
        InputStream inputStream = openFileInput("config.txt");

        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((receiveString = bufferedReader.readLine()) != null) {
                stringBuilder.append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    } catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

如果有人可以提供帮助,我将不胜感激任何提示或解决方法。它给出的确切错误是它无法解析该方法。当我试图自己研究它时,他们提到了一些关于上下文的东西,但我在代码中找不到它的例子。

openFileInput() is a method on Context。您会注意到 onReceive() 的第二个参数是 Context。因此,您可以在 Context 对象上调用 openFileInput()

话虽如此,请注意 onReceive() 是在主应用程序线程上调用的,在主应用程序线程上执行磁盘 I/O 并不是一个好主意。