android > SMS 短信数据库访问

.java

package test.mft;

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

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.widget.TabHost;


public class TestActivity extends Activity {
    /** Called when the activity is first created. */
	 
	Context Tcontext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		Tcontext = TestActivity.this; 
		getSMSInPhone();
		//
		
	}
	private Cursor getSMSInPhone() {  
        Uri SMS_CONTENT = Uri.parse("content://sms/");  
        String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };  
        // type : 1-> 接收  , 2->发送
        Cursor cursor = Tcontext.getContentResolver().query(SMS_CONTENT, projection, null, null, "date desc");   // 获取手机短信   

        while (cursor.moveToNext()) {   
            System.out.println("--sms-- : " + "address:"+cursor.getString(cursor.getColumnIndex("address"))+
            		 "\nperson:"+getPeopleNameFromPerson(cursor.getString(cursor.getColumnIndex("address")))+
            		 "\nbody:"+cursor.getString(cursor.getColumnIndex("body"))+
            		 "\ndate:"+cursor.getString(cursor.getColumnIndex("date"))+
            		 "\ntype:"+cursor.getString(cursor.getColumnIndex("type")) );   
        }  

        return cursor;  
    } 

	private String getPeopleNameFromPerson(String address){
		if(address == null || address == ""){
			return "( no address )\n";
		}
		
		String strPerson = "null";
		String[] projection = new String[] {Phone.DISPLAY_NAME, Phone.NUMBER};
		
		Uri uri_Person = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, address);	// address 手机号过滤
		Cursor cursor = getContentResolver().query(uri_Person, projection, null, null, null);
		
		if(cursor.moveToFirst()){
			int index_PeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME);
			String strPeopleName = cursor.getString(index_PeopleName);
			strPerson = strPeopleName;
		}
		else{
			strPerson = address;
		}
		cursor.close();
		
		return strPerson;
	}
	
	
}

 

--sms-- : address:1388888888
person:王三
body:我是信息内容?
date:1365658438100
type:1

 

 

权限加上


 

 

 

 

 

 

你可能感兴趣的:(android)