Search code examples
javaandroidfunctionbroadcastreceiver

How do I call a function with parameters in MainActivity from non-dynamic receiver?


In my MainActivity, I have the following function:

public void writefile (FileOutputStream fOut, String fileName, OutputStreamWriter osw, String message){
    try {
        fOut = openFileOutput(fileName, MODE_WORLD_READABLE);
        osw = new OutputStreamWriter(fOut);
        osw.write(message);
        osw.flush();
        osw.close();
    }
    catch (IOException ioe){
        ioe.printStackTrace();
    }
}

My SMS receiver for this app MUST be non-dynamic (no layout), and within my onReceive method, I try to call the function:

writefile(fOut, ib1, osw, message);

My parameters are all ok, but 'writefile' becomes red and 'cannot be resolved.' So I tried changing it to:

MainActivity.writefile(fOut, ib1, osw, message);

But now, 'writefile' is underlined with a static/non-static problem. In order to get rid of this error, I tried making the function static in MainActivity, but then, 'openFileOutput' starts to complain about static/non-static.

I was willing to put the function into my Receiver class too to be called every time from the same class, but functions like 'openFileOutput' cannot be resolved because the Receiver can only extend BroadcastReceiver.

I was also willing to call another activity upon onReceiver and do my work there, but I couldn't find a way to implement that either.

Can anybody please offer me any help on this issue? Thanks in advance.


Solution

  • openFileOutput() is a method on Context. Your activity is a Context, and your receiver gets a Context passed to it in onReceive(). So, make the writefile() method static, and pass in a Context as a parameter. Then, call openFileOutput() on the passed-in Context. Your activity can use the static method by passing in this for the Context. Your receiver can use the static method by passing in the Context you get in onReceive().

    Then, make sure that you are only calling writefile() on a background thread.