温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-05-25 09:31:04 来源:亿速云 阅读:206 作者:小新 栏目:移动开发

小编给大家分享一下android ContentResolver如何获取手机电话号码和短信内容,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

通过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是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。

看完了这篇文章,相信你对“android ContentResolver如何获取手机电话号码和短信内容”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI