以下代码不支持多音字,请慎重使用。
package com.tc.sjcj.TC_Provider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
public class SingleConvertPinyinClass {
/**
* 汉字转成拼音缩写
*
* @param activity
* 活动界面
* @param chinese
* 要转的中文汉字
* @return
*/
public String chineseParseToPinYin(Context context, String chinese) {
ContentValues values = new ContentValues();
Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
String name = chinese;
if (name.length() != 0) {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.GIVEN_NAME, name);
context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
String result = hanziToPinyin(context, rawContactId);
delete(context, rawContactId);
return result;
} else {
return null;
}
}
private String hanziToPinyin(Context context, long rawContactId) {
String result = "";
String Where = ContactsContract.RawContacts.CONTACT_ID + " =" + rawContactId;
String[] projection = { "sort_key" };
Cursor cur = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, Where, null, null);
int pinyin1 = cur.getColumnIndex("sort_key");
cur.moveToFirst();
String pinyin = cur.getString(pinyin1);
boolean tried = true;
for (int i = 0; i < pinyin.length(); i++) {
String temp = pinyin.substring(i, i + 1);
if (temp.matches("[a-zA-Z]") && tried == true) {
result = result + temp;
tried = false;
} else if (temp.matches("[a-zA-Z]") == false) {
tried = true;
}
}
String message = result.toUpperCase();
return message;
}
private void delete(Context context, long rawContactId) {
context.getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null);
}
}