2012-02-15 33 views
2

我在清單文件中註冊了一個接收器,希望看看即將到來的短消息是否有我的應用程序存儲的消息。但我在接收器中訪問文件時遇到困難。似乎自從我擴展BroadcastReceiver,我無法讀取文件。但我不太確定。有人可以幫助我。以下是代碼在廣播接收器中讀取文件

public class BootReceiver extends BroadcastReceiver { 


    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED"; 

    String password; 

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

     try { 
      InputStream in = openFileInput("string.txt"); 
      if (in != null) { 
       InputStreamReader tmp = new InputStreamReader(in); 
       BufferedReader reader = new BufferedReader(tmp); 
       String str; 
       StringBuilder buf = new StringBuilder(); 
       while ((str = reader.readLine()) != null) { 
        buf.append(str); 
       } 
       in.close(); 
       password = buf.toString(); 
      } 
     } 
     catch (Throwable t) { 
      ; 
     } 


     if (intent.getAction().equals(ACTION)) { 

      Intent initial = new Intent(context, SMSActivity.class); 
      initial.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      context.startActivity(initial); 
     } 

    } 

} 
+0

你得到任何錯誤? – Farhan 2012-02-15 08:25:43

+0

是的,有關於openFileInput的錯誤:方法openFileInout(String)是未定義的類型BootReceiver – jedichen 2012-02-16 02:55:53

回答

2

而不是openFileInput("string.txt");嘗試使用context.getApplicationContext().openFileInput("string.txt");

+0

謝謝它的作品!但我仍然不知道爲什麼它可以工作。讀寫功能只在上下文中定義?有沒有在互聯網上解釋這種事情的任何參考? – jedichen 2012-02-16 03:27:33

+0

是的只是指的是Android文檔。這是Android開發人員常見的誤解。沒有一個方法可以在java中存在,而不需要在某處定義它。因此,您在「活動」中使用的「findViewById」和「openFileInput」等方法實際上在「上下文」中定義,並且每個活動都是上下文。看到這裏:http://developer.android.com/reference/android/app/Activity.html – 2012-02-16 07:31:44