我正在爲android構建一個簡單的備份應用程序,並且此代碼讀取並將手機內存中的所有消息存儲到csv文件,最初我顯示的是不確定的進度欄,但是應用程序的用戶可能會對此感到不耐煩(如果他們的信息太多),所以我想添加一個確定的水平進度條向他們展示實際的進度,我一直在嘗試做一些事情,但現在我不能得到它的權利,我知道我應該在異步任務類中使用onProgressUpdate方法,但我真的不知道如何實現,所以我得到了很多的例外,所以我試圖在一個不同的沒有方法,這是下面的代碼如何更新異步進度欄任務
package daniel.idea.backup;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
public ArrayList<String> smsBuffer = new ArrayList<String>();
String smsFile = "SMS"+".csv";
Integer x = 0;
static Integer Total = 0;
//Initialize the various ui elements
Button contact,msg;
ProgressDialog pb;
TextView total;
static Context mContext;
//Method to fetch and write the contacts to the .vcf file
public static String getVCF() {
final String vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
phones.moveToFirst();
Total = phones.getCount();
for (int i = 0; i < phones.getCount(); i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
Log.d("Vcard", VCard);
mFileOutputStream.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return phones.getCount()+ " Contacts";
}
//This is the method used to get the sms and save them to a file
private String backupSMS(){
smsBuffer.clear();
Uri mSmsinboxQueryUri = Uri.parse("content://sms");
Cursor cursor1 = mContext.getContentResolver().query(
mSmsinboxQueryUri,
new String[] { "_id", "thread_id", "address", "person", "date",
"body", "type" }, null, null, null);
//startManagingCursor(cursor1);
String[] columns = new String[] { "_id", "thread_id", "address", "person", "date", "body",
"type" };
if (cursor1.getCount() > 0) {
String count = Integer.toString(cursor1.getCount());
Log.d("Count",count);
while (cursor1.moveToNext()) {
String messageId = cursor1.getString(cursor1
.getColumnIndex(columns[0]));
String threadId = cursor1.getString(cursor1
.getColumnIndex(columns[1]));
String address = cursor1.getString(cursor1
.getColumnIndex(columns[2]));
String name = cursor1.getString(cursor1
.getColumnIndex(columns[3]));
String date = cursor1.getString(cursor1
.getColumnIndex(columns[4]));
String msg = cursor1.getString(cursor1
.getColumnIndex(columns[5]));
String type = cursor1.getString(cursor1
.getColumnIndex(columns[6]));
smsBuffer.add(messageId + ","+ threadId+ ","+ address + "," + name + "," + date + " ," + msg + " ,"
+ type);
}
generateCSVFileForSMS(smsBuffer);
}
return cursor1.getCount() + "Messages";
}
private void generateCSVFileForSMS(ArrayList<String> list)
{
try
{
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + smsFile;
FileWriter write = new FileWriter(storage_path);
write.append("messageId, threadId, Address, Name, Date, msg, type");
write.append('\n');
for (String s : list)
{
write.append(s);
write.append('\n');
}
write.flush();
write.close();
}
catch (NullPointerException e)
{
System.out.println("Nullpointer Exception "+e);
// e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mContext = MainActivity.this;
Cursor phones_total = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
//This gets the count of all the contacts in the phone memory
Integer total_contacts = phones_total.getCount();
contact = (Button) findViewById (R.id.bt_contacts);
msg = (Button) findViewById (R.id.bt_messages);
total = (TextView) findViewById (R.id.tv_total);
contact.setOnClickListener(this);
msg.setOnClickListener(this);
total.setText(total_contacts +" Contacts");
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bt_contacts:
MyTask task = new MyTask();
task.execute("Param 1","Param2","Param3");
break;
case R.id.bt_messages:
SmsTask task2 = new SmsTask();
task2.execute();
}
}
public class MyTask extends AsyncTask<String, Integer, String>{
@Override
protected void onPreExecute() {
//make the progressDialog
pb = new ProgressDialog(MainActivity.this);
pb.setTitle("Please wait ...");
pb.setIndeterminate(false);
pb.setMessage("Backing up contacts...");
pb.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pb.setProgress(0);
pb.setMax(100);
pb.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
mContext = MainActivity.this;
String total_c = getVCF();
//Increment the progress dialog
for(int i = 0; i < Total; i++){
publishProgress(i);
}
return total_c;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//hide the progress bar and display a toast message
pb.dismiss();
Toast.makeText(MainActivity.this, result + " Succesfully backed up", Toast.LENGTH_LONG).show();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pb.incrementProgressBy(values[0]);
values[0]++;
}
}
public class SmsTask extends AsyncTask <String,Integer,String>{
protected void onPreExecute() {
//show the progress bar
pb = ProgressDialog.show(MainActivity.this, "Processing",
"please wait", true);
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
mContext = MainActivity.this;
String total_sms = backupSMS();
return total_sms;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//hide the progress bar and display a toast
pb.dismiss();
Toast.makeText(MainActivity.this, result + " Succesfully backed up", Toast.LENGTH_LONG).show();
}
}
}
進度條顯示出來,但它沒有更新...除此之外代碼工作完美...請我需要建議我如何實現一個確定的progess欄到此代碼。謝謝
編輯:我已經經歷了發佈的兩個答案,並且我已經重寫了我的代碼,而不是更新它的進度條,只是在完成時跳過從0到100,請有人指出我在此代碼中的錯誤
我認爲我們可以從'onPreExecute()'和'onPostExecute()',也訪問UI。 :) – 2014-09-22 11:11:28
啊等一下,我弄錯了。我只想着進度更新......:D – PKlumpp 2014-09-22 11:12:09