我想致电用户联系人列表。然后,他们将选择联系人发送短信。我很难理解如何在发送SMS时保存联系人以供使用。任何帮助,将不胜感激。这是我的代码到底以下。
package com.example.practiceapp;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class Dollar extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dollar);
}
//@Override
//public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.activity_dollar, menu);
//return true;
//}
public void contacts(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
int PICK_CONTACT=0;
startActivityForResult(intent, PICK_CONTACT);
}
}
我使用了Android Essentials:使用联系人
它提供了一个用于选择电子邮件地址的工作示例。
使用联系人选择器获得联系ID后,关键代码是:
// query for everything email
cursor = getContentResolver().query(
Email.CONTENT_URI, null,
Email.CONTACT_ID + "=?",
new String[]{id}, null);
id
是从联系人选择器返回的联系人ID(如教程中所述)。要获取电话数据,您需要将其更改为:
// query for everything phone
cursor = getContentResolver().query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID + "=?",
new String[]{id}, null);
请注意,联系人可以具有多个电话号码,因此您必须构建第二个对话框才能选择特定的电话号码。
ArrayList<String> phoneNumbers = new ArrayList<String>();
String name = "";
String number = "";
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
// Get all phone numbers for the person
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
name = cursor.getString(nameIdx); // get the name from the cursor
number = cursor.getString(numberIdx); // get the phone number from the cursor
phoneNumbers.add(number);
Log.v(DEBUG_TAG, "Got name: " + name + " phone: "
+ number);
} while (cursor.moveToNext());
showPhoneNumberSelectionDialog(name,phoneNumbers);
} else {
Log.w(DEBUG_TAG, "No results");
}
(或者您可以根据需要从上述代码中调整光标读取)
private void showPhoneNumberSelectionDialog(String name,
final ArrayList<String> phoneNumbers) {
1. Build an AlertDialog to pick a number from phoneNumbers (with'name' in the title);
2. Send an SMS to the number
}
构建警报对话框并不难,但涉及将阵列列表转换为字符串数组。请参阅转换ArrayList到字符串[]
发送SMS非常容易。网上有很多示例。
so q&amp; a(如何在Android 2.0上读取联系人)也是很好的背景,但最终我没有使用任何代码。