Android 将字符串写入广播接收器中的文件

发布于 2024-12-27 05:01:52 字数 2187 浏览 1 评论 0原文

我已经设置了广播接收器来捕获短信。该类使用 Toast 显示消息,但我需要将字符串写入文件,但因为它不是活动,所以不起作用。

有没有办法将“短信”字符串写入广播接收器内的文件?

如果没有,谁能想出另一种方法将短信保存到文件中,而无需在收到短信时运行应用程序?

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

        }

    }

}

语法错误“MODE_PRIVATE 无法解析为变量”
- 该代码仅在活动类中使用时才有效

清单文件:

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

        </intent-filter> 
    </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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒与心事 2025-01-03 05:01:52

尝试将 context 传递到 SaveMessage...

SaveMessage(context, str);

...并更改您的 SaveMessage 方法,如下所示...

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
}

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
}
怕倦 2025-01-03 05:01:52

您可以使用以下方法获取数据的应用程序私有 File 对象:(

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

使用 onReceive 中传递的 Context 对象。)然后您可以使用以下命令打开并写入它:来自java.io的标准类:

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

卸载应用程序时,外部文件目录中的文件将被删除。

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.

单调的奢华 2025-01-03 05:01:52

您无权写入 SDCard。

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

这里有一个很好的代码示例
http://androidgps.blogspot.com/2008 /09/writing-to-sd-card-in-android.html

但是,我不会写入 SD 卡的根目录。最好写入 /data/[application package]/

将 [application package] 替换为您的包,例如:com.example.helloandroid

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文