AsyncTask小结
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
mLoadingView.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... params) {
mDatas = TrafficProvider.getTraffics(TrafficActivity.this);
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
}
@Override
protected void onPostExecute(Void result) {
mLoadingView.setVisibility(View.GONE);
mLv.setAdapter(new TrafficAdapter());
}
}.execute();
// 加载进度条
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
SmsProvider.smsBackup(this, new OnSmsListener() {
@Override
public void onPre() {
dialog.show();
}
@Override
public void onProgress(int max, int progress) {
dialog.setMax(max);
dialog.setProgress(progress);
}
@Override
public void onFinish(boolean success) {
dialog.dismiss();
if (success) {
Toast.makeText(CommonToolActivity.this, "备份成功", 0).show();
} else {
Toast.makeText(CommonToolActivity.this, "备份失败", 0).show();
}
}
});
public static void smsBackup(final Context context,
final OnSmsListener listener) {
new AsyncTask<Void, Integer, Boolean>() {
@Override
protected void onPreExecute() {
if (listener != null) {
listener.onPre();
}
}
@Override
protected Boolean doInBackground(Void... params) {
boolean flag = true;
try {
// 读短信,放到sd卡中
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.parse("content://sms");
String[] projection = { "address", "date", "read", "type",
"body" };
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
// select * from table where name = 'zs';
Cursor cursor = cr.query(uri, projection, selection,
selectionArgs, sortOrder);
// 放到list中
List<SmsBean> list = new ArrayList<SmsBean>();
if (cursor != null) {
int count = cursor.getCount();
int progress = 0;
publishProgress(count, progress);
while (cursor.moveToNext()) {
String address = cursor.getString(0);
long date = cursor.getLong(1);
int read = cursor.getInt(2);
int type = cursor.getInt(3);
String body = cursor.getString(4);
SmsBean bean = new SmsBean(address, date, read,
type, body);
list.add(bean);
publishProgress(count, ++progress);
}
}
cursor.close();
// json到sd卡中
Gson gson = new Gson();
String json = gson.toJson(list);
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(new File(
Environment.getExternalStorageDirectory(),
"sms.json")));
bw.write(json);
} catch (Exception e) {
e.printStackTrace();
} finally {
StreamUtils.closeIO(bw);
}
} catch (Exception e) {
flag = false;
}
return flag;
}
@Override
protected void onProgressUpdate(Integer... values) {
Integer max = values[0];
Integer progress = values[1];
if (listener != null) {
listener.onProgress(max, progress);
}
}
@Override
protected void onPostExecute(Boolean result) {
if (listener != null) {
listener.onFinish(result);
}
}
}.execute();
}