2008年2月13日 星期三

How to Android? Step3: Get contacts data from android.provider


如何透過Google的android.provider來取得手機通訊錄資料?

1. AndroidManifest.xml : 在此xml檔案加入下列籃色那個安全性設定,不然會一直發生安全性錯誤!

<?xml version="1.0" encoding="utf-8"?>
<manifest android="http://schemas.android.com/apk/res/android"
package="com.google.test">
<uses-permission android:name="android.permission.READ_CONTACTS" />

<application icon="@drawable/icon">
<activity class=".hello" label="@string/app_name">
<intent-filter>
<action value="android.intent.action.MAIN">
<category value="android.intent.category.LAUNCHER">
</category>
</action>
</intent-filter>
</activity>
</application></manifest>



2. hello.java : 在Activity java檔中加入下列籃色部份程式碼!
package com.google.test;

import android.app.Activity;
import android.database.Cursor;
import com.google.test.R;
import android.os.Bundle;
import android.widget.TextView;

public class hello extends Activity {
private TextView tv;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
tv =(TextView) findViewById(R.id.test);

// An array specifying which columns to return.
String[] projection = new String[] {
android.provider.BaseColumns._ID,
android.provider.Contacts.PeopleColumns.NAME,
android.provider.Contacts.PhonesColumns.NUMBER
};

// Best way to retrieve a query; returns a managed query.
Cursor managedCursor = managedQuery( android.provider.Contacts.Phones.CONTENT_URI,
projection, //Which columns to return.
null, // WHERE clause--we won't specify.
android.provider.Contacts.PeopleColumns.NAME + " ASC"); // Order-by clause.
getColumnData(managedCursor);

}

private void getColumnData(Cursor cur){
String name;
String phoneNumber;
int nameColumn = cur.getColumnIndex(android.provider.Contacts.PeopleColumns.NAME);
int phoneColumn = cur.getColumnIndex(android.provider.Contacts.PhonesColumns.NUMBER);

String imagePath;
tv.setText("");
while (cur.next()) {
name = cur.getString(nameColumn);
phoneNumber = cur.getString(phoneColumn);

tv.append(name+" : "+phoneNumber+"\n");
}
}
}


3. main.xml : 在layout資料夾下的main.xml檔案加入下列籃色部份,來顯示抓到的資料!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>

沒有留言: