我正在尝试使用以下代码将每个传入的短信保存在外部存储器的文本文件中。 对于小消息或我工作,但当消息变长,并有很多空格这个代码只保存文本文件中的最后几行.i无法找出问题。 任何想法?
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody().toString();
//file name will be current time for uniquess
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd_MMMM_yyyy__HH_mm_ss__a");
String fileName = sdf.format(c.getTime());
File myFile = new File("/sdcard//SaveSMS/"+getName(senderNum,context)+"//"+ fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
// Append Body SMS to Stream
myOutWriter.append(message);
myOutWriter.close();
fOut.close();
Toast.makeText(context,"This SMS will save in SaveSMS\\"+senderNum, 1).show();
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
错误示例:如果有人发短信
1 1 1 2 3
4
5 6 6 7 8 9
7 6 5
此代码仅保存
6 5
答案 0 :(得分:0)
是否覆盖现有文件中的数据?尝试更换
new FileOutputStream(myFile);
与
new FileOutputStream(myFile, true);