Search code examples
androidalarmmanagerbufferedreaderandroid-context

Reading a File from Cache in Android Alarmmanager


I want to save a File to my Cache. I use a BufferedWriter for this. I get my path by using:

CacheDir.getPath() + "/" + "Example.txt"

where CacheDir is CacheDir = getCacheDir();

Now I want to Read from this File using a Reader Method inside an Alarmmanager/Broadcastreceiver.

I use: localLoadUpString = readTextFile(CacheDir.getPath()+"/"+"Example.txt"); in my AlarmReceiver I get the File CacheDir by: CacheDir = context.getCacheDir();

When i use Log to see if my paths are correct, everything looks quite nice, but my localLoadUpString never gets a String back from my reader Method ( reader Method works fine in the other (normal) activity)

Did I make a mistake by using the wrong context?


Solution

  • The "correct" context probably depends on how you registered your BroadcastReceiver.

    1. If you declared it in your AndroidManifest.xml, the context passed into onReceive() is the ApplicationContext.
    2. If you dynamically registered the BroadcastReceiver at runtime via context.registerReceiver(), the context passed into onReceive() is the same context that was used to call registerReceiver().

    In case number 2, you can always call context.getApplicationContext() to retrieve the Application Context.

    Since I can't get a feel for what you're trying to do from where, my initial recommendation would be to try context.getApplicationContext().getCacheDir() in your onReceive() call.