讀取系統聯絡人電話_ListActivity

1.AndroidManifest.xml程式碼

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app.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>

2.MainActivity.java程式碼

import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> data;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c = super.getContentResolver().query(Phone.CONTENT_URI, null,
null, null, null);
data = new ArrayList<HashMap<String, String>>();
prepareData(c);
// startManagingCursor(c);
ListAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] {
Phone.DISPLAY_NAME, Phone.NUMBER }, new int[] {
android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
}

public void prepareData(Cursor c) {

c.moveToFirst();
while (!c.isAfterLast()) {
HashMap hm = new HashMap();
hm.put(Phone.DISPLAY_NAME,
c.getString(c.getColumnIndex(Phone.DISPLAY_NAME)));
hm.put(Phone.NUMBER, c.getString(c.getColumnIndex(Phone.NUMBER)));
data.add(hm);
c.moveToNext();
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String n = ((TextView) v.findViewById(android.R.id.text1)).getText()
.toString();
String p = ((TextView) v.findViewById(android.R.id.text2)).getText()
.toString();
Intent it = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + p));
this.startActivity(it);
}
}

沒有留言: