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

所属分类: 软件编程 / Android 阅读数: 30
收藏 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 HapticFeedback(震动反馈)

下面小编就为大家带来一篇老生常谈Android HapticFeedback(震动反馈)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详谈OnTouchListener与OnGestureListener的区别

下面小编就为大家带来一篇详谈OnTouchListener与OnGestureListener的区别。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android仿知乎悬浮功能按钮FloatingActionButton效果

前段时间在看属性动画,恰巧这个按钮的效果可以用属性动画实现,下面通过本文给大家分享adroid仿知乎悬浮功能按钮FloatingActionButton效果,需要的朋友参考下吧
收藏 0 赞 0 分享

解决Android V7后自定义Toolbar、ActionBar左侧有空白问题

这篇文章主要介绍的Android V7后自定义Toolbar、ActionBar左侧有空白问题的解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android常见控件使用详解

这篇文章主要为大家详细介绍了Android常见控件的使用方法,包括ProgressBar进度条控件、AlertDialog对话框控件等,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android实现简洁的APP更新dialog数字进度条

这篇文章主要为大家详细介绍了Android实现简洁的APP更新dialog数字进度条,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android 判断当前语言环境是否是中文环境

本文主要介绍了Android 判断当前语言环境是否是中文环境的方法。具有很好的参考价值。下面跟着小编一起来看下吧
收藏 0 赞 0 分享

详谈Android中Matrix的set、pre、post的区别

下面小编就为大家带来一篇详谈Android中Matrix的set、pre、post的区别。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android实现登录界面记住密码的存储

这篇文章主要为大家详细介绍了Android SharedPreferrences实现登录界面记住密码的存储,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android 使用SharedPreferrences储存密码登录界面记住密码功能

Android存储方式有很多种,在这里所用的存储方式是SharedPreferrences, 其采用了Map数据结构来存储数据,以键值的方式存储,可以简单的读取与写入,下面通过实例代码给大家讲解下,需要的朋友参考下吧
收藏 0 赞 0 分享
查看更多