2

I registered a receiver in manifest file want to see if the coming sms has the message stored by my application. but I have difficulties in accessing files in the receiver. it seems since i extends BroadcastReceiver, i cannot read files. but i'm not quite sure. how somebody can help me. below is the code

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

    }

}
run
  • 1,170
  • 7
  • 14
jedichen
  • 91
  • 1
  • 7
  • yes, there is error about the openFileInput: the method openFileInout(String) is undefined for the type BootReceiver – jedichen Feb 16 '12 at 02:55

1 Answers1

2

Instead of openFileInput("string.txt"); try using context.getApplicationContext().openFileInput("string.txt");.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Thank you it works!!! but I still don't know why it can work. the read and write function is only defined in context? is there any reference on the internet explaining this kind of thing? – jedichen Feb 16 '12 at 03:27
  • Yes just refer to the android documentation. This is a common misconception in the Android developers. Not a single method can exist in java without it being defined somewhere. Thus methods like 'findViewById` and `openFileInput` that you used in Activities are actually defined in `Context`, and every Activity is a Context. See here: http://developer.android.com/reference/android/app/Activity.html – Boris Strandjev Feb 16 '12 at 07:31