android ContentResolver获取手机电话号码和短信内容

所属分类: 软件编程 / Android 阅读数: 26
收藏 0 赞 0 分享

通过ContentResolver 获取到手机的联系人跟手机短信信息并显示出来,供大家参考,具体内容如下

1、实现的代码:

package com.example.phone; 
 
 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.ContactsContract; 
import android.provider.ContactsContract.PhoneLookup; 
import android.app.Activity; 
import android.content.ContentResolver; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteException; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
 
 
public class MainActivity extends Activity implements OnClickListener{ 
 
  private TextView text; 
  private Button button; 
  private Button sms; 
  HashMap<String, Object> map = new HashMap<String, Object>(); 
  List<String> con = new ArrayList<String>(); 
  String msg;//联系人姓名+号码 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);  
    initUI();     
  } 
 
  private void initUI() { 
    // TODO Auto-generated method stub  
    text = (TextView)findViewById(R.id.text); 
    button = (Button)findViewById(R.id.button);//获取手机电话号码 
    button.setOnClickListener(this); 
    sms = (Button)findViewById(R.id.sms);//获取手机短信信息 
    sms.setOnClickListener(this); 
  } 
  @Override 
  public void onClick(View v) { 
    // TODO Auto-generated method stub 
    switch(v.getId()){ 
      case R.id.button: 
        getPhoneNumber();//获取手机电话号码 
        break; 
      case R.id.sms://获取手机短信内容 
        getSmsMessage(); 
        Map<String,Object> item = new HashMap<String,Object>(); 
        for(int i= 0;i<con.size();i++){ 
          text.setText(item.put("con", con.get(i))+"");//仅显示一条 
          System.out.println("ningshengcai:"+item.put("con", con.get(i)));//打印显示全部数据      
        } 
        break; 
      default : 
        break; 
    } 
  } 
  /** 
   * 获取手机联系人号码 
   */ 
  public void getPhoneNumber(){ 
    // smslist=getListView();  
    //得到ContentResolver对象   
    ContentResolver cr = getContentResolver();    
    //取得电话本中开始一项的光标   
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);   
    while (cursor.moveToNext())   
    {   
      // 取得联系人名字   
      int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);   
      String name = cursor.getString(nameFieldColumnIndex);   
      //name += (name);   
      // 取得联系人ID   
      String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));   
      Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
          ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "+ contactId, null, null);     
      // 取得电话号码(可能存在多个号码)   
      while (phone.moveToNext())   
      {   
        String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
        System.out.println(name+":"+strPhoneNumber);                     
        msg += name+":"+strPhoneNumber+"\n"; 
        text.setText(msg); 
      }       
      phone.close();   
    }   
    cursor.close();  
  } 
  /** 
   * 获取短信信息 
   * @return smsBuilder.toString() 
   */ 
  @SuppressWarnings("unused") 
  public String getSmsMessage(){   
     
    final String SMS_URI_ALL  = "content://sms/";    
    final String SMS_URI_INBOX = "content://sms/inbox";   
    final String SMS_URI_SEND = "content://sms/sent";   
    final String SMS_URI_DRAFT = "content://sms/draft";   
       
    StringBuilder smsBuilder = new StringBuilder();   
       
    try{   
      ContentResolver cr = getContentResolver();   
      String[] projection = new String[]{"_id", "address", "person",    
          "body", "date", "type"};   
      Uri uri = Uri.parse(SMS_URI_ALL);   
      Cursor cur = cr.query(uri, projection, null, null, "date desc");   
     
      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 = "";   
          }   
          //System.out.println("nsc :"+name+":"+phoneNumber+":"+smsbody+":"+date+":"+type +"\n"); 
          String smsmsg = name+":"+phoneNumber+":"+smsbody+":"+date+":"+type+"\n"; 
          con.add(smsmsg);          
          if(smsbody == null) smsbody = "";    
        }while(cur.moveToNext());   
      } else {   
        smsBuilder.append("no result!");   
      }   
          
      smsBuilder.append("getSmsInPhone has executed!");   
    } catch(SQLiteException ex) {   
      Log.d("SQLiteException in getSmsInPhone", ex.getMessage());   
    }   
    return smsBuilder.toString();   
  }   
} 

2、代码布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" 
  tools:context=".MainActivity" > 
   
  <Button  
    android:id="@+id/button" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/ph"/> 
  <Button  
    android:id="@+id/sms" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/sms"/> 
  <ScrollView 
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"> 
    <TextView 
      android:id="@+id/text" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"       
      android:text="@string/hello_world" /> 
         
  </ScrollView> 
 
</LinearLayout> 

3、需要用到的权限

<uses-permission android:name="android.permission.READ_CONTACTS" />  
  <uses-permission android:name="android.permission.WRITE_SMS" />  
  <uses-permission android:name="android.permission.READ_SMS" />  
  <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Android中加入名片扫描功能实例代码

这篇文章主要介绍了Android中加入名片扫描功能实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Android仿微信发表说说实现拍照、多图上传功能

这篇文章主要为大家详细介绍了Android仿微信发表说说实现拍照、多图上传功能,使用Retrofit2.0技术,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

设置Android系统永不锁屏永不休眠的方法

在进行Android系统开发的时候,有些特定的情况需要设置系统永不锁屏,永不休眠。本篇文章给大家介绍Android 永不锁屏,开机不锁屏,删除设置中休眠时间选项,需要的朋友一起学习吧
收藏 0 赞 0 分享

Android Retrofit 2.0框架上传图片解决方案

这篇文章主要介绍了Android Retrofit 2.0框架上传一张与多张图片解决方案,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android自定义等待对话框

这篇文章主要为大家详细介绍了Android自定义等待对话框的实现方法,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android中Window添加View的底层原理

这篇文章主要介绍了Android中Window添加View的底层原理,需要的朋友可以参考下
收藏 0 赞 0 分享

Android调用系统默认浏览器访问的方法

这篇文章主要介绍了Android调用系统默认浏览器访问的方法的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Android开发退出程序的方法汇总

Android程序有很多Activity,比如说主窗口A,调用了子窗口B,子窗口B又调用子窗口C,back返回子窗口B后,在B中如何关闭整个Android应用程序呢? 下面脚本之家小编就给大家介绍android开发退出程序的几种方法,感兴趣的朋友参考下吧
收藏 0 赞 0 分享

Android程序开发中单选按钮(RadioGroup)的使用详解

在android程序开发中,无论是单选按钮还是多选按钮都非常的常见,接下来通过本文给大家介绍Android程序开发中单选按钮(RadioGroup)的使用,需要的朋友参考下吧
收藏 0 赞 0 分享

Android实现仿网易今日头条等自定义频道listview 或者grideview等item上移到另一个view中

这篇文章主要介绍了Android实现仿网易今日头条等自定义频道listview 或者grideview等item上移到另一个view中 的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多