使用Contact数据模型来批量插入联系人主要需要contact数据模型的以下两文件:
com.Android.contacts.model下的:
EntitySet.java
EntityDelta.java
EntitySet在Android 4.0中已经被改名为EntityDeltaList.
我自己的代码在MainActivity.java,DialogResolver.java和ContactPersistTask.java。
注意:需要在AndroidManifest.xml加入写contacts的权限。
写contacts的权限为:
<uses-permission android:name="android.permission.READ_CONTACTS" />
读contacts的权限为:
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
文件1MainActivity.java文件
package com.teleca.robin.Contact;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements DialogResolver{
final static String TAG="robin";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.Button01);
OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
doAddAction();
}
};
button.setOnClickListener(listener);
editText=(EditText)findViewById(R.id.editText);
editText.setText("100");
}
EditText editText;
void doAddAction() {
String content=editText.getText().toString();
int count=0;
try{
count=Integer.parseInt(content);
}catch(NumberFormatException e)
{
Toast.makeText(this, "please input a Number for Contacts count!",
Toast.LENGTH_SHORT).show();
}
final ContactPersistTask task = new ContactPersistTask(this);
task.execute(count);
}
public void showDialog(Dialog dialog)
{
dialog.show();
}
public void dismissDialog(Dialog dialog)
{
dialog.dismiss();
}
public Activity getActivity(){
return this;
}
}
文件2
DialogResolver.java文件
package com.teleca.robin.Contact;
import android.app.Dialog;
public interface DialogResolver{
public void showDialog(Dialog dialog);
public void dismissDialog(Dialog dialog);
}
注意:对于任何实现了DialogResolver的类,要求该类必须是Activity。
文件3
布局文件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
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/editText"
android:layout_width="100dp"
android:layout_height="wrap_content"
/>
<Button android:text="@string/add" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
文件4
strings.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string>please input the number to add for contact!</string>
<string>ContactGenerator</string>
<string>add</string>
<string>insert contact</string>
<string>waiting</string>
</resources>