获取系统的联系人信息
一 UI Code
<RelativeLayout 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"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="21dp"
android:layout_marginTop="60dp"
android:layout_toLeftOf="@+id/textView1"
android:text="插入短信" />
</RelativeLayout>
二 Permission Code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.insertsms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!--实现读与写短信的权限 -->
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.insertsms.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
三 Logical Code
package com.itheima.readsms;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv_content);
}
//读取系统里面的短信
public void click(View view){
//1.利用内容提供者 中间人 获取用户的短信数据.
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://sms/"); //根据分析 代表的是所有的短信的路径
Cursor cursor = resolver.query(uri, new String[]{"address","date","body","type"}, null, null, null);
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()){
String address =cursor.getString(0);
String date = cursor.getString(1);
String body = cursor.getString(2);
String type = cursor.getString(3);
//弹出一个对话框--提示短信发送成功
Toast.makeText(MainActivity.this, "读取1短信成功", Toast.LENGTH_LONG).show();
System.out.println("address="+address+"-date-"+date+"--body-"+body+"--type-"+type);
sb.append(address+"--"+date+"---"+body+"---"+type);
sb.append("\n");
System.out.println("Hello");
}
cursor.close();
//弹出一个对话框--提示短信发送成功
Toast.makeText(MainActivity.this, "读取2短信成功", Toast.LENGTH_LONG).show();
tv.setText(sb.toString());
}
}