read files in broadcast receiver

2019-07-23 06:11发布

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

    }

}

1条回答
倾城 Initia
2楼-- · 2019-07-23 06:55

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

查看更多
登录 后发表回答