`
hualikejava
  • 浏览: 169829 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

android中的短信操作

阅读更多

在android读取短信并进行相应的管理时,可以进行短信箱删除,但是这个删除先得到TheardId跟这个threadID进行删除短信

 

 

在getContentResolver进行查询。代码如下

用到权限:  
    <uses-permission android:name="android.permission.READ_SMS"/>

  <uses-permission android:name="android.permission.WRITE_SMS"/>这个是写短信用到的。

 

写道
package com.jdjw.test;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
/**
*
* 读取第一条短信并删除
*
*/
public class TestSMSActivity extends Activity {

private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = this;
/*
* 删除第一条短信
long id = getThreadId();
Uri mUri=Uri.parse("content://sms/conversations/" + id);
mContext.getContentResolver().delete(mUri, null, null);
*/
getSMSInfo();
}
/**
* 读取第一条短信并删除
* @return
*/
private long getThreadId() {
long threadId = 0;
String SMS_READ_COLUMN = "read";
String SORT_ORDER = "date DESC";//时间降序查找
int count = 0;
Cursor cursor = mContext.getContentResolver().query(
Uri.parse("content://sms/inbox"),
new String[] { "_id", "thread_id", "address", "person", "date",
"body" }, null, null, SORT_ORDER);

if (cursor != null) {
try {
count = cursor.getCount();
if (count > 0) {
cursor.moveToFirst();
threadId = cursor.getLong(1);
}
} finally {
cursor.close();
}
}
Log.i("threadId", String.valueOf(threadId));

return threadId;
}

/**
* 得到全部短信
*/
private void getSMSInfo(){
Cursor cur = mContext.getContentResolver().query(Uri.parse("content://sms/inbox"), new String[]{
"_id","address","person","date","body","type"
},null,null, "date DESC");

StringBuilder smsBuilder = new StringBuilder();
if (cur.moveToFirst()) {
String name;
String phoneNumber;
String smsbody;
String date;
String type;

int nameColumn = cur.getColumnIndex("person");
int phoneNumberColumn = cur.getColumnIndex("address");
int smsbodyColumn = cur.getColumnIndex("body");
int dateColumn = cur.getColumnIndex("date");
int typeColumn = cur.getColumnIndex("type");
do{
name = cur.getString(nameColumn);
phoneNumber = cur.getString(phoneNumberColumn);
smsbody = cur.getString(smsbodyColumn);

SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
date = dateFormat.format(d);

int typeId = cur.getInt(typeColumn);
if(typeId == 1){
type = "接收";
} else if(typeId == 2){
type = "发送";
} else {
type = "";
}

smsBuilder.append("[");
smsBuilder.append(name+",");
smsBuilder.append(phoneNumber+",");
smsBuilder.append(smsbody+",");
smsBuilder.append(date+",");
smsBuilder.append(type);
smsBuilder.append("] ");

if(smsbody == null) smsbody = "";
}while(cur.moveToNext());
}
System.out.println(smsBuilder.toString());

}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics