Jake Graham Arnold
Jake Graham Arnold

Reputation: 1446

Android write String to file within Broadcast Receiver

I have set up a Broadcast Receiver to capture SMS messages. The Class display the message using Toast but I need to write the String to a file but because it's not an Activity it doesn't work.

Is there a way I can write the "sms message" String to a file within the Broadcast Receiver?

If not can anyone think of another way to save an SMS message to a file without the app running when the text message is received?

   public class SMSReciever extends BroadcastReceiver {

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

   //---get the SMS message passed in---

   Bundle bundle = intent.getExtras();        
   SmsMessage[] msgs = null;
   String str = "";            
   if (bundle != null)
   {

   //---retrieve the SMS message received---

       Object[] pdus = (Object[]) bundle.get("pdus");
       msgs = new SmsMessage[pdus.length];            
       for (int i=0; i<msgs.length; i++){
           msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
           str += SMS from " + msgs[i].getOriginatingAddress();                     
           str += " :";
           str += msgs[i].getMessageBody().toString();
           str += "\n";        
       }


       //---display the new SMS message---

       Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

        //---Save SMS message---

          SaveMessage(str);

              }
        }


       public void SaveMessage(String message) {

    FileOutputStream FoutS = null;

    OutputStreamWriter outSW = null;

    try {

        FoutS = openFileOutput("Message.dat", MODE_PRIVATE);

        outSW = new OutputStreamWriter(FoutS);

        outSW.write(message);

        outSW.flush();

    }

    catch (Exception e) {

        e.printStackTrace();

    }

    finally {

        try {

            outSW.close();

            FoutS.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

syntax error "MODE_PRIVATE cannot be resolved to a variable"
- The code only works when used in an activity class

manifest file:

        <receiver android:name=".SMSReciever"> 
        <intent-filter> 
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED"
                android:enabled="true" /> 

        </intent-filter> 
    </receiver>

This is my first ever post so I hope I did everything correctly, Thanks in advance this site has helped me so much already.

Upvotes: 0

Views: 3550

Answers (3)

JustinDanielson
JustinDanielson

Reputation: 3185

You don't have permission to write to the SDCard.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

A good code sample is here
http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html

However, I wouldn't write to the root of the SD Card. It's good practice to write to /data/[application package]/

Replace [application package] with your package, ex: com.example.helloandroid

Upvotes: 0

Squonk
Squonk

Reputation: 48871

Try passing context into SaveMessage...

SaveMessage(context, str);

...and change your SaveMessage method as follows...

public void SaveMessage(Context context, String message) {

    FileOutputStream FoutS = null;
    OutputStreamWriter outSW = null;

    try {
        FoutS = context.openFileOutput("Message.dat", Context.MODE_PRIVATE);

        // Rest of try block here
    }
    // 'catch' and 'finally' here
}

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234807

You can use the following to obtain an application-private File object for your data:

File outFile = new File(getExternalFilesDir(null), "DemoFile.jpg");

(Use the Context object passed in onReceive.) Then you can open and write to it using standard classes from java.io:

Writer writer = new FileWriter(outFile);
. . .

The files in your external files directory will be deleted when your app is uninstalled.

Upvotes: 0

Related Questions