无法在BroadcastReceiver中使用openFileInput

时间:2015-06-14 18:12:31

标签: android broadcastreceiver

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

公共类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;
}

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

1 个答案:

答案 0 :(得分:0)

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

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