这是我的代码:
private void readSMS() throws IOException {
// TODO Auto-generated method stub
Log.d("Read SMS","Called");
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.parse("content://sms/inbox");
String smsBackup;
Cursor messagesCursor = cr.query(uri, new String[] { "_id","address","body","person"}, null,null, null);
smsBackup = "SMS Back UP (Total Message(s)::"+messagesCursor.getCount()+") \n\n";
String smsfile = "SMS" + "_" + System.currentTimeMillis()+".txt";
storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + smsfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path,true);
mFileOutputStream.write(smsBackup.getBytes());
String name = null,smsString;
int smsCounter = 1;
if(messagesCursor.getCount() > 0){
while(messagesCursor.moveToNext()){
name = null;
name = getName(messagesCursor.getString(messagesCursor.getColumnIndex("address")));
if(name==null)
name = "Sender : " + messagesCursor.getString(messagesCursor.getColumnIndex("address"));
smsString = "SMS No : "+smsCounter+"\nSender : "+name +"\n"+ "Message : "+messagesCursor.getString(messagesCursor.getColumnIndex("body")) + "\n\n";
mFileOutputStream.write(smsString.getBytes());
Log.d("Message","::"+smsString+"Length::"+smsString.length());
smsString = null;
Log.d("Message","written::"+smsCounter);
smsCounter++;
}
messagesCursor.close();
file = new File(storage_path);
mFileOutputStream.close();
Log.d("MSGFile","written");
}
}
private String getName(String number1) {
// TODO Auto-generated method stub
Log.d("get name","Called");
//Log.d("get name",number1);
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cur.getCount() > 0){
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
//Log.e("Name new:", name);
String number = names.getString(indexNumber);
//Log.e("Number new:","::"+number);
if(number1.contains(number)){
cur.close();
return name;
}
} while (names.moveToNext());
}
cur.close();
return null;
}
我也收到警告:W/CursorWrapperInner(22787): Cursor finalized without prior close()