实例介绍
【实例简介】可以分局省份城市批量生成联系人,通话记录和短信数据。
【实例截图】
【核心代码】
package com.example.phonelocatiion;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import android.accounts.Account;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts;
import android.provider.Telephony;
import android.provider.Telephony.Sms;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
public class AutoGeneratePhone extends Activity implements OnClickListener {
Spinner spinner_pv, spinner_cy, spinner_cr;
Set<String> pvdata = new HashSet<String>(), crdata = new HashSet<String>(), cydata = new HashSet<String>();
List<String> pv_list_data = new ArrayList<String>(), cy_list_data = new ArrayList<String>(),
cr_list_data = new ArrayList<String>();
static boolean iscopy = false;
private ArrayAdapter<String> pv_adapter, cy_adapter, cr_adapter;
public static Handler handler;
private String selectPv, selectCy, selectCr;
Button btn_contact, btn_delete_contact, btn_mms, btn_calllogs;
ImageView bgimage;
private final static String KEY_LONG_ID = "key_begin_long_id";
private static int xuhao = 0;
private final static int MAX_PHONE_NUMBER = 1000;
private final static int MAX_MMS_NUMBER = 1000;
private final static int MAX_CallLogs_NUMBER = 3000;
private final static int ONCE_LOAD_PHONE_NUMBER = 500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.auto_generate_phone);
handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
pv_adapter = new ArrayAdapter<String>(AutoGeneratePhone.this, android.R.layout.simple_spinner_item,
pv_list_data);
pv_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_pv.setAdapter(pv_adapter);
cy_adapter = new ArrayAdapter<String>(AutoGeneratePhone.this, android.R.layout.simple_spinner_item,
cy_list_data);
cy_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_cy.setAdapter(cy_adapter);
cr_adapter = new ArrayAdapter<String>(AutoGeneratePhone.this, android.R.layout.simple_spinner_item,
cr_list_data);
cr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_cr.setAdapter(cr_adapter);
break;
case 1:
new loadDataAsyncTask().execute("");
break;
case 2:
Toast.makeText(AutoGeneratePhone.this, "正在拷贝数据,请稍后...", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(AutoGeneratePhone.this, "数据拷贝完毕", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(AutoGeneratePhone.this, "正在生成号码,请稍后...", Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(AutoGeneratePhone.this, "正在删除,请稍后...", Toast.LENGTH_SHORT).show();
break;
}
super.handleMessage(msg);
};
};
btn_contact = (Button) findViewById(R.id.btn_contacts);
btn_contact.setOnClickListener(this);
btn_delete_contact = (Button) findViewById(R.id.btn_delete_contacts);
btn_delete_contact.setOnClickListener(this);
btn_mms = (Button) findViewById(R.id.btn_mms);
btn_mms.setOnClickListener(this);
btn_calllogs = (Button) findViewById(R.id.btn_calllog);
btn_calllogs.setOnClickListener(this);
bgimage = (ImageView) findViewById(R.id.btn_readmms);
bgimage.setOnClickListener(this);
spinner_pv = (Spinner) findViewById(R.id.spinner_province);
spinner_cy = (Spinner) findViewById(R.id.spinner_city);
spinner_cr = (Spinner) findViewById(R.id.spinner_carrior);
spinner_pv.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selectPv = pv_list_data.get(arg2);
cy_list_data.clear();
cy_list_data.addAll(getCitysByProvince(selectPv));
Collections.sort(cy_list_data, new PinyinComparator());
spinner_cy.setAdapter(cy_adapter);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_cy.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selectCy = cy_list_data.get(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_cr.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selectCr = cr_list_data.get(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
IntentFilter filter = new IntentFilter();
filter.addAction("xuxin_action_test");
registerReceiver(receiver, filter);
test();
}
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("xuxin", "-----------------------------------------------------------------------------------");
// test();
// testGroups();
// Log.i("xuxin","########################################################################################");
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
RunningTaskInfo cinfo = runningTasks.get(0);
ComponentName component = cinfo.topActivity;
Log.i("xuxin", "current activity is " component.getClassName());
}
};
private void test() {
Uri uri = ContactsContract.RawContacts.CONTENT_URI;// Uri.withAppendedPath(ContactsContract.AUTHORITY_URI,
// "raw_contacts_all");
String[] projections = new String[] { RawContacts._ID, Contacts.DISPLAY_NAME, RawContacts.SOURCE_ID,
RawContacts.CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE };
String selection = null;// RawContacts.ACCOUNT_NAME "=? and "
// RawContacts.ACCOUNT_TYPE "=? and deleted=0
// ";
String[] selectionArgs = null;// ListUtil.newArray(account.name,
// account.type);
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(uri, projections, selection, selectionArgs, "_id DESC");
// this.getContentResolver().delete(uri, selection, selectionArgs);
if (null != cursor && cursor.moveToFirst()) {
Log.i("xuxin", "begin --- " getStartId(this) " last --- " cursor.getString(0));
} else {
Log.i("xuxin", "cursor null le");
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private void testGroups() {
String[] projection = new String[] { Groups._ID, Groups.SOURCE_ID, Groups.TITLE, RawContacts.ACCOUNT_NAME,
RawContacts.ACCOUNT_TYPE };
String selection = Groups.DELETED "=0";
String[] selectionArgs = null;
String sortOrder = Groups._ID;
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(Groups.CONTENT_URI, projection, selection, selectionArgs,
sortOrder);
if (null != cursor) {
Log.i("xuxin", "test group size --- " cursor.getCount());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
protected void onResume() {
if (isDBexist()) {
pv_list_data.clear();
cy_list_data.clear();
cr_list_data.clear();
new loadDataAsyncTask().execute("");
} else {
new copyDBAsyncTask().execute("");
}
super.onResume();
}
class loadDataAsyncTask extends AsyncTask<Object, Object, Object> {
@Override
protected void onPreExecute() {
pvdata.clear();
cydata.clear();
crdata.clear();
cydata.clear();
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
handler.sendEmptyMessage(0);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
initData(AutoGeneratePhone.this);
return null;
}
}
class copyDBAsyncTask extends AsyncTask<Object, Object, Object> {
@Override
protected void onPreExecute() {
iscopy = true;
handler.sendEmptyMessage(2);
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
handler.sendEmptyMessage(3);
iscopy = false;
new loadDataAsyncTask().execute("");
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
GetDataBasePath(AutoGeneratePhone.this);
return null;
}
}
private void initData(Context context) {
PhoneLocalDBHelper dbHelper = PhoneLocalDBHelper.getInstance(context);
SQLiteDatabase readdb = dbHelper.getReadableDatabase();
Cursor c = readdb.query("locals", new String[] { "province", "city", "cardtype" }, null, null, null, null,
"province ASC", null);
while (c != null && c.moveToNext()) {
pvdata.add(c.getString(0));
cydata.add(c.getString(0) "," c.getString(1));
crdata.add(c.getString(2));
}
pv_list_data.addAll(pvdata);
Collections.sort(pv_list_data, new PinyinComparator());
if (pv_list_data.size() <= 0) {
// new copyDBAsyncTask().execute("");
return;
}
cy_list_data.addAll(getCitysByProvince(pv_list_data.get(0)));
cr_list_data.addAll(crdata);
Collections.sort(cy_list_data, new PinyinComparator());
Collections.sort(cr_list_data, new PinyinComparator());
Collections.reverse(cr_list_data);
pvdata.clear();
crdata.clear();
selectPv = pv_list_data.get(0);
selectCy = cy_list_data.get(0);
selectCr = cr_list_data.get(0);
if (c != null) {
c.close();
}
if (readdb != null) {
readdb.close();
}
}
private boolean isDBexist() {
return new File("/data/data/com.example.phonelocatiion/databases/phonelocal.db").exists();
}
private void GetDataBasePath(Context context) {
String DB_PATH = String.format("/data/data/%1$s/databases/", context.getPackageName());
String DB_NAME = "phonelocal.db";
String outFileName = DB_PATH DB_NAME;
File file = new File(DB_PATH);
if (!file.exists()) {
file.mkdirs();
}
try {
InputStream myInput = context.getAssets().open(DB_NAME);
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e) {
Log.i("xuxin", "copy db exp -- " e.toString());
e.printStackTrace();
}
}
// @Override
// public boolean onMenuItemSelected(int featureId, MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_db:
// startActivity(new Intent(this, MainActivity.class));
// break;
// default:
// return false;
// }
// return super.onMenuItemSelected(featureId, item);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
// return super.onCreateOptionsMenu(menu);
// }
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_contacts:
Log.i("xuxin", "-----------------------------------------------------------------------------------");
test();
testGroups();
new insertContactsAsyncTask().execute("");
break;
case R.id.btn_delete_contacts:
new deleteContactsAsyncTask().execute("");
break;
case R.id.btn_mms:
new insertMmsAsyncTask().execute("");
break;
case R.id.btn_calllog:
new insertCallAsyncTask().execute("");
break;
case R.id.btn_readmms:
HashMap<String,Boolean> isTimeOut = new HashMap<String,Boolean>();
android.util.Log.i("xuxin","call -- 01");
String s = "xuxin";
isTimeOut.put(s, null);
android.util.Log.i("xuxin","call -- 04");
isTimeOut.containsKey(s);
android.util.Log.i("xuxin","call -- 02");
//isTimeOut.put(s, false);
if(isTimeOut.get(s)!=null && isTimeOut.get(s)){
android.util.Log.i("xuxin","call -- 055");
}
android.util.Log.i("xuxin","call -- 03 bool = " isTimeOut.get(s));
break;
}
}
class insertContactsAsyncTask extends AsyncTask<Object, Object, Object> {
long starttime = System.currentTimeMillis();
@Override
protected void onPreExecute() {
handler.sendEmptyMessage(4);
btn_contact.setEnabled(false);
btn_delete_contact.setEnabled(false);
xuhao = 0;
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
Toast.makeText(AutoGeneratePhone.this,
"随机生成号码耗时" ((System.currentTimeMillis() - starttime) / 1000) "秒钟", Toast.LENGTH_LONG).show();
btn_contact.setEnabled(true);
btn_delete_contact.setEnabled(true);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
try {
insertContacts(AutoGeneratePhone.this);
} catch (RemoteException | OperationApplicationException e) {
Log.i("xuxin", "extp-- " e.toString());
xuhao = 0;
e.printStackTrace();
}
return null;
}
}
class deleteContactsAsyncTask extends AsyncTask<Object, Object, Object> {
long starttime = System.currentTimeMillis();
@Override
protected void onPreExecute() {
handler.sendEmptyMessage(5);
btn_contact.setEnabled(false);
btn_delete_contact.setEnabled(false);
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
Toast.makeText(AutoGeneratePhone.this, "删除号码耗时" ((System.currentTimeMillis() - starttime) / 1000) "秒钟",
Toast.LENGTH_LONG).show();
btn_contact.setEnabled(true);
btn_delete_contact.setEnabled(true);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
deleteContacts(AutoGeneratePhone.this);
return null;
}
}
private void insertContacts(Context context) throws RemoteException, OperationApplicationException {
List<String> alls = getContactsNum(context, MAX_PHONE_NUMBER);
ArrayList<String> opsfenkai = new ArrayList<String>();
int times = MAX_PHONE_NUMBER / ONCE_LOAD_PHONE_NUMBER;
for (int i = 0; i < times; i ) {
Log.i("xuxin", "insert 500 tiao le --- " i);
opsfenkai.clear();
opsfenkai.addAll(alls.subList(i * ONCE_LOAD_PHONE_NUMBER, (i 1) * ONCE_LOAD_PHONE_NUMBER));
BatchAddContact(AutoGeneratePhone.this, opsfenkai);
}
int yushu = MAX_PHONE_NUMBER % ONCE_LOAD_PHONE_NUMBER;
if (yushu != 0) {
opsfenkai.clear();
opsfenkai.addAll(alls.subList(alls.size() - yushu, alls.size()));
BatchAddContact(AutoGeneratePhone.this, opsfenkai);
}
test();
xuhao = 0;
}
String defaultSmsPkg, mySmsPkg;
private void insertMms(Context context) throws RemoteException, OperationApplicationException {
List<String> alls = getContactsNum(context, MAX_MMS_NUMBER);
ArrayList<String> opsfenkai = new ArrayList<String>();
int times = MAX_MMS_NUMBER / ONCE_LOAD_PHONE_NUMBER;
for (int i = 0; i < times; i ) {
Log.i("xuxin", "insert 500 tiao le --- " i);
opsfenkai.clear();
opsfenkai.addAll(alls.subList(i * ONCE_LOAD_PHONE_NUMBER, (i 1) * ONCE_LOAD_PHONE_NUMBER));
BatchAddMms(AutoGeneratePhone.this, opsfenkai);
}
int yushu = MAX_MMS_NUMBER % ONCE_LOAD_PHONE_NUMBER;
if (yushu != 0) {
opsfenkai.clear();
opsfenkai.addAll(alls.subList(alls.size() - yushu, alls.size()));
BatchAddMms(AutoGeneratePhone.this, opsfenkai);
}
}
private List<String> getContactsNum(Context context, int num) {
List<String> subnums = new ArrayList<String>();
PhoneLocalDBHelper dbHelper = PhoneLocalDBHelper.getInstance(context);
SQLiteDatabase readdb = dbHelper.getReadableDatabase();
Cursor c = readdb.query("phonelocale", new String[] { "subphonenum" }, "province=? and city=? and cardtype=?",
new String[] { selectPv, selectCy, selectCr }, "subphonenum", null, null, null);
while (c != null && c.moveToNext()) {
subnums.add(c.getString(0));
}
if (c != null) {
c.close();
}
if (readdb != null) {
readdb.close();
}
return genenrateConactsFromSubNum(subnums, num);
}
private List<String> genenrateConactsFromSubNum(List<String> subnums, int num) {
List<String> phones = new ArrayList<String>();
Random random = new Random();
if (num <= subnums.size()) {
for (int i = 0; i < num; i ) {
int j = random.nextInt(num);
phones.add(subnums.get(j) getFourRandom());
}
} else {
int sizeOfoneSubNum = num / subnums.size();
int mainSize = num % subnums.size();
for (int i = 0; i < subnums.size(); i ) {
for (int j = 0; j < sizeOfoneSubNum; j ) {
phones.add(subnums.get(i) getFourRandom());
}
}
for (int i = 0; i < mainSize; i ) {
phones.add(subnums.get(random.nextInt(subnums.size())) getFourRandom());
}
}
return phones;
}
private Set<String> getCitysByProvince(String province) {
Set<String> citys = new TreeSet<String>();
for (String s : cydata) {
if (province.equals(s.trim().split(",")[0])) {
citys.add(s.split(",")[1]);
}
}
return citys;
}
public long addOneMms(String phoneNum, String body) {
Log.i("insertmms", "insert one mms--------- phoneNum = " phoneNum " body =" body);
ContentValues values = new ContentValues();
Uri uri = Uri.parse("content://sms/");
values.put("address", phoneNum);
values.put("type", (new Random().nextInt(2) 1));
values.put("date", System.currentTimeMillis());
values.put("body", body);
uri = getContentResolver().insert(uri, values);
long mmsId = ContentUris.parseId(uri);
Log.i("insertmms", "mmsid--------- " mmsId);
return mmsId;
}
private static char getRandomChar() {
String str = "";
int hightPos; //
int lowPos;
Random random = new Random();
hightPos = (176 Math.abs(random.nextInt(39)));
lowPos = (161 Math.abs(random.nextInt(93)));
byte[] b = new byte[2];
b[0] = (Integer.valueOf(hightPos)).byteValue();
b[1] = (Integer.valueOf(lowPos)).byteValue();
try {
str = new String(b, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println("错误");
}
return str.charAt(0);
}
private String getRadomBody() {
// StringBuffer sb = new StringBuffer();
// for (int i = 0; i < 70; i ) {
// sb.append(getRandomChar() "");
// }
return "言哮表郡狐烘磊姐葬腑熔敦屏射腥兢捅陷汲葫盗不狰芒劳澳斡拄喘蠢楞指裙榷占慢搭盗轻甩粥涂择肮少湃撕馒颇很摇惩琳寿搓净联赫猜拎雀猛娇蝶率册扬嗓搅坛";
}
public long addOneContact(String name, String phoneNum) {
ContentValues values = new ContentValues();
Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
if (name != "") {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.GIVEN_NAME, name);
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}
if (phoneNum != "") {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, phoneNum);
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}
return rawContactId;
}
/**
* 批量添加通讯录
*
* @throws OperationApplicationException
* @throws RemoteException
*/
public void BatchAddContact(Context context, List<String> list)
throws RemoteException, OperationApplicationException {
xuhao ;
long rawContactInsertIndex = addOneContact(xuhao "_Contact", list.get(0));
if (xuhao == 1)
setStartId(context, rawContactInsertIndex);
list.remove(0);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (String number : list) {
xuhao ;
rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null).withValue(RawContacts.ACCOUNT_NAME, null)
.withYieldAllowed(true).build());
// 添加姓名
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, (int) rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, xuhao "_Contact").withYieldAllowed(true).build());
// 添加号码
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, (int) rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE).withValue(Phone.NUMBER, number)
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).withValue(Phone.LABEL, "").withYieldAllowed(true)
.build());
}
if (ops != null) {
ContentProviderResult[] results = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Log.i("xuxin", "results size -- " results.length);
// // 真正添加
// ContentProviderResult[] results = context.getContentResolver()
// .applyBatch(ContactsContract.AUTHORITY, ops);
// Log.i("xuxin","results size -- " results.length);
// for (ContentProviderResult result : results) {
// GlobalConstants
// .PrintLog_D("[GlobalVariables->]BatchAddContact "
// result.uri.toString());
// }
}
}
public void BatchAddMms(Context context, List<String> list) {
long mmsIndex = addOneMms(list.get(0), getRadomBody());
list.remove(0);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (String number : list) {
mmsIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Uri.parse("content://sms/")).withValue("address", number)
.withValue("type", (new Random().nextInt(2) 1)).withValue("date", System.currentTimeMillis())
.withValue("body", getRadomBody()).withYieldAllowed(true).build());
}
if (ops != null) {
Log.i("insertmms", "applyBatch --------- begin");
ContentProviderResult[] results = null;
try {
results = context.getContentResolver().applyBatch("sms", ops);
Log.i("insertmms", "applyBatch --------- end");
} catch (RemoteException e) {
Log.i("insertmms", "RemoteException --------- " e.toString());
e.printStackTrace();
} catch (OperationApplicationException e) {
Log.i("insertmms", "OperationApplicationException --------- " e.toString());
e.printStackTrace();
}
Log.i("insertmms", "results size -- " (results == null ? -1 : results.length));
// // 真正添加
// ContentProviderResult[] results = context.getContentResolver()
// .applyBatch(ContactsContract.AUTHORITY, ops);
// Log.i("xuxin","results size -- " results.length);
// for (ContentProviderResult result : results) {
// GlobalConstants
// .PrintLog_D("[GlobalVariables->]BatchAddContact "
// result.uri.toString());
// }
}
}
private void deleteContacts(Context context) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentProviderOperation op = null;
Uri uri = null;
int num = 0;// 删除影响的行数
ContentResolver resolver = context.getContentResolver();
resolver.delete(
Uri.parse(ContactsContract.RawContacts.CONTENT_URI.toString() "?"
ContactsContract.CALLER_IS_SYNCADAPTER "=true"),
RawContacts._ID ">=" getStartId(context) " and " RawContacts._ID "<"
(getStartId(context) MAX_PHONE_NUMBER),
null);
// 删除Data表的数据
uri = Uri.parse(Data.CONTENT_URI.toString() "?" ContactsContract.CALLER_IS_SYNCADAPTER "=true");
op = ContentProviderOperation
.newDelete(uri).withSelection(Data.RAW_CONTACT_ID ">=" getStartId(context) " and "
Data.RAW_CONTACT_ID "<" (getStartId(context) MAX_PHONE_NUMBER), null)
.withYieldAllowed(true).build();
ops.add(op);
// 删除RawContacts表的数据
uri = Uri.parse(RawContacts.CONTENT_URI.toString() "?" ContactsContract.CALLER_IS_SYNCADAPTER "=true");
op = ContentProviderOperation
.newDelete(RawContacts.CONTENT_URI).withSelection(Data.RAW_CONTACT_ID ">=" getStartId(context)
" and " Data.RAW_CONTACT_ID "<" (getStartId(context) MAX_PHONE_NUMBER), null)
.withYieldAllowed(true).build();
ops.add(op);
// //删除Contacts表的数据
// uri = Uri.parse(Contacts.CONTENT_URI.toString() "?"
// ContactsContract.CALLER_IS_SYNCADAPTER "=true");
// op = ContentProviderOperation.newDelete(uri)
// .withSelection(Contacts._ID ">=" getStartId(context), null)
// .withYieldAllowed(true)
// .build();
// ops.add(op);
// 执行批量删除
try {
ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);
for (ContentProviderResult result : results) {
num = result.count;
Log.i("xuxin", "删除影响的行数:" result.count);
}
} catch (Exception e) {
Log.i("xuxin", e.getMessage());
}
}
public void deleteOneContact(long rawContactId) {
getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null);
}
private void setStartId(Context context, long id) {
context.getSharedPreferences("shared_phone_local", MODE_PRIVATE).edit().putLong(KEY_LONG_ID, id).commit();
}
private long getStartId(Context context) {
return context.getSharedPreferences("shared_phone_local", MODE_PRIVATE).getLong(KEY_LONG_ID, -1);
}
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
handler = null;
super.onDestroy();
}
public String getFourRandom() {
Random random = new Random();
String fourRandom = random.nextInt(10000) "";
int randLength = fourRandom.length();
if (randLength < 4) {
for (int i = 1; i <= 4 - randLength; i )
fourRandom = "0" fourRandom;
}
return fourRandom;
}
class insertMmsAsyncTask extends AsyncTask<Object, Object, Object> {
long starttime = System.currentTimeMillis();
@Override
protected void onPreExecute() {
btn_mms.setEnabled(false);
defaultSmsPkg = Telephony.Sms.getDefaultSmsPackage(AutoGeneratePhone.this);
mySmsPkg = AutoGeneratePhone.this.getPackageName();
if (!defaultSmsPkg.equals(mySmsPkg)) {
// 如果这个App不是默认的Sms App,则修改成默认的SMS APP
// 因为从Android 4.4开始,只有默认的SMS APP才能对SMS数据库进行处理
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, mySmsPkg);
startActivity(intent);
}
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
Toast.makeText(AutoGeneratePhone.this, "随机生成短信" ((System.currentTimeMillis() - starttime) / 1000) "秒钟",
Toast.LENGTH_LONG).show();
btn_mms.setEnabled(true);
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsPkg);
startActivity(intent);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
try {
insertMms(AutoGeneratePhone.this);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
return null;
}
}
// ------------------------------------------------- call
// logs-----------------------------------------------
class insertCallAsyncTask extends AsyncTask<Object, Object, Object> {
long starttime = System.currentTimeMillis();
@Override
protected void onPreExecute() {
btn_calllogs.setEnabled(false);
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
Toast.makeText(AutoGeneratePhone.this,
"随机生成通话记录" ((System.currentTimeMillis() - starttime) / 1000) "秒钟", Toast.LENGTH_LONG).show();
btn_calllogs.setEnabled(true);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
try {
insertCallLogs(AutoGeneratePhone.this);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
return null;
}
}
class deleteResFilesTask extends AsyncTask<Object, Object, Object> {
long starttime = System.currentTimeMillis();
@Override
protected void onPreExecute() {
btn_calllogs.setEnabled(false);
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
Toast.makeText(AutoGeneratePhone.this,
"随机生成通话记录" ((System.currentTimeMillis() - starttime) / 1000) "秒钟", Toast.LENGTH_LONG).show();
btn_calllogs.setEnabled(true);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
try {
insertCallLogs(AutoGeneratePhone.this);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
return null;
}
}
class deleteSrcFilesTask extends AsyncTask<Object, Object, Object> {
long starttime = System.currentTimeMillis();
@Override
protected void onPreExecute() {
btn_calllogs.setEnabled(false);
super.onPreExecute();
}
@Override
protected void onPostExecute(Object result) {
Toast.makeText(AutoGeneratePhone.this,
"随机生成通话记录" ((System.currentTimeMillis() - starttime) / 1000) "秒钟", Toast.LENGTH_LONG).show();
btn_calllogs.setEnabled(true);
super.onPostExecute(result);
}
@Override
protected Object doInBackground(Object... params) {
try {
insertCallLogs(AutoGeneratePhone.this);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
return null;
}
}
private void insertCallLogs(Context context) throws RemoteException, OperationApplicationException {
List<String> alls = getContactsNum(context, MAX_CallLogs_NUMBER);
ArrayList<String> opsfenkai = new ArrayList<String>();
int times = MAX_CallLogs_NUMBER / ONCE_LOAD_PHONE_NUMBER;
for (int i = 0; i < times; i ) {
Log.i("xuxin", "insert 500 tiao le --- " i);
opsfenkai.clear();
opsfenkai.addAll(alls.subList(i * ONCE_LOAD_PHONE_NUMBER, (i 1) * ONCE_LOAD_PHONE_NUMBER));
BatchAddCallLogs(AutoGeneratePhone.this, opsfenkai);
}
int yushu = MAX_CallLogs_NUMBER % ONCE_LOAD_PHONE_NUMBER;
if (yushu != 0) {
opsfenkai.clear();
opsfenkai.addAll(alls.subList(alls.size() - yushu, alls.size()));
BatchAddCallLogs(AutoGeneratePhone.this, opsfenkai);
}
}
public void BatchAddCallLogs(Context context, List<String> list) {
long calllogIndex = addOneCallLog(list.get(0));
list.remove(0);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (String number : list) {
calllogIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(CallLog.Calls.CONTENT_URI)
.withValue(CallLog.Calls.NUMBER, number).withValue(CallLog.Calls.DATE, System.currentTimeMillis())
.withValue(CallLog.Calls.DURATION, new Random().nextInt(100))
.withValue(CallLog.Calls.TYPE, new Random().nextInt(3) 1)// 未接
.withValue(CallLog.Calls.NEW, new Random().nextInt(2))// 0已看1未看
.withYieldAllowed(true).build());
}
if (ops != null) {
Log.i("insertmms", "applyBatch --------- begin");
ContentProviderResult[] results = null;
try {
results = context.getContentResolver().applyBatch(CallLog.AUTHORITY, ops);
Log.i("insertmms", "applyBatch --------- end");
} catch (RemoteException e) {
Log.i("insertmms", "RemoteException --------- " e.toString());
e.printStackTrace();
} catch (OperationApplicationException e) {
Log.i("insertmms", "OperationApplicationException --------- " e.toString());
e.printStackTrace();
}
Log.i("insertmms", "results size -- " (results == null ? -1 : results.length));
// // 真正添加
// ContentProviderResult[] results = context.getContentResolver()
// .applyBatch(ContactsContract.AUTHORITY, ops);
// Log.i("xuxin","results size -- " results.length);
// for (ContentProviderResult result : results) {
// GlobalConstants
// .PrintLog_D("[GlobalVariables->]BatchAddContact "
// result.uri.toString());
// }
}
}
public long addOneCallLog(String phoneNum) {
Log.i("insertmms", "insert one mms--------- phoneNum = ");
ContentValues values = new ContentValues();
Uri uri = CallLog.Calls.CONTENT_URI;
values.put(CallLog.Calls.NUMBER, phoneNum);
values.put(CallLog.Calls.DATE, System.currentTimeMillis());
values.put(CallLog.Calls.DURATION, new Random().nextInt(100));
values.put(CallLog.Calls.TYPE, new Random().nextInt(3) 1);// 未接
values.put(CallLog.Calls.NEW, new Random().nextInt(2));// 0已看1未看
uri = getContentResolver().insert(uri, values);
long callid = ContentUris.parseId(uri);
Log.i("insertmms", "mmsid--------- " callid);
return callid;
}
//----------------------------- read mms-----------------------------------------
public final String SMS_URI_ALL = "content://sms/"; // 所有短信
final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
final String SMS_URI_SEND = "content://sms/sent"; // 已发送
final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表
}
好例子网口号:伸出你的我的手 — 分享!
相关软件
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论