2015-06-14 31 views
1

我不熟悉編碼,我試圖自己學習它,但我遇到了我正在開發的無法在廣播接收器中使用openFileInput的應用程序中的問題。下面是代碼:無法在廣播接收器中使用openFileInput

公共類AlarmReceiver擴展廣播接收器{

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



} 

//結束320交織

​​

//讀取320交織開始

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; 
} 

如果任何人都可以幫助我將不勝感激任何提示或解決辦法。它給出的確切錯誤是它無法解決該方法。當我試圖自己研究它時,他們提到了一些關於上下文的內容,但我無法在代碼中找到它的一個例子。

回答

0

openFileInput() is a method on Context。您會注意到onReceive()的第二個參數是Context。因此,您可以在Context對象上調用openFileInput()

也就是說,請注意在主應用程序線程上調用onReceive(),並且在主應用程序線程上執行磁盤I/O不是一個好主意。

+0

謝謝,但我必須做什麼,使openFileInput在那裏工作?我需要它,以便使用個人集名稱發送消息。 –

+0

@ThomasHolland:「我需要做些什麼才能使openFileInput在那裏工作?」 - 將'Context'作爲參數傳遞給'readFromFilename()'。由於您未顯示使用'readFromFilename()'的位置或方式,因此難以進一步提供幫助。 – CommonsWare

+0

readFromFilename用於訪問文件config.txt,該文件將返回文件中的名稱。所以在openFileInput不再被註冊爲錯誤之後,設置了一個變量String name = readFromFilename(); 。這有幫助嗎? –