我有一个带按钮的活动 . 单击其中一个按钮会从另一个类调用静态方法 . 然后,此方法调用一系列以菊花链形式连接的AsyncTasks . 就像在第一个任务的OnPostExecute中,我将调用一个新的AsyncTask,然后在第二个AsyncTask的OnPostExecute中,我再次调用一个新的AsyncTask . 这持续了大约15个级别 . 我需要在这些任务运行时显示进度对话框并显示相应的状态(百分比) . 我是通过在第一个AsyncTask的OnPreExecute上创建一个新的ProgressDialog来实现的 . 我的问题是当设备旋转或进入睡眠状态时,ProgressDialog消失,当我从最终的OnPostExecute调用dismiss()时会引发异常 .
这是我的代码(低至2级Asynctasks)
活动:
private class OnButtonMenuClick implements OnClickListener {
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.textViewDownload:
downloadReferenceFiles();
break;
case R.id.textViewProductNotes:
showProductNotes();
break;
case R.id.textViewCustomerNotes:
showCustomerNotes();
break;
case R.id.textViewAdjustOrders:
orderAdjustments();
break;
case R.id.textViewUploadOrders:
uploadDataToServer();
break;
case R.id.textViewToolsReconciliationIcon:
cashCount();
break;
case R.id.textViewToolsExpensesIcon:
expensesEntry();
break;
case R.id.textViewSalesSummaryIcon:
showSalesSummary();
break;
case R.id.textViewInventoryIcon:
showInventory();
break;
case R.id.textViewInventoryByVolumeIcon:
showInventoryByVolume();
break;
}
}
}
public void downloadReferenceFiles() {
ReferenceFilesDownloader.downloadData(ToolsActivity.this, true);
}
参考文件下载类(单独文件)
import java.util.ArrayList;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class ReferenceFilesDownloader {
private static ProgressDialog progress;
private static Context context;
private static boolean includeInventory;
public static void downloadData(Context ctx) {
context = ctx;
includeInventory = false;
new AsyncCheckServerDate().execute();
}
public static void setContext(Context ctx) {
context = ctx;
}
public static void downloadData(Context ctx, boolean inventory) {
context = ctx;
includeInventory = inventory;
new AsyncCheckServerDate().execute();
}
public static String buildProgress(int value, int max) {
int percent = (int)(((double)value / (double)max) * 100);
String current = value + " of " + max + " (" + percent + "% completed)";
return current;
}
public static void createProgress() {
if (progress == null) {
progress = new ProgressDialog(context);
progress.setIndeterminate(false);
progress.setCancelable(false);
progress.setCanceledOnTouchOutside(false);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
if (!progress.isShowing()) {
progress.show();
}
}
protected static class AsyncCheckServerDate extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String today = "";
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetDateToday();
JSONParser parser = new JSONParser();
today = parser.parseDateToday(jsonObj);
}
catch (NullPointerException e) {
}
catch (Exception e) {
}
return today;
}
@Override
protected void onPreExecute() {
//progress.show(manager, tag)
/*progress = new ProgressDialog(context);
progress.setMessage("Verifying server date. Please wait...");
progress.setCancelable(false);
progress.setCanceledOnTouchOutside(false);
progress.show();*/
}
@Override
protected void onPostExecute(String result) {
if (result.equals(StaticHolder.today())) {
new AsyncCustomers().execute();
}
else {
AppMessages.showMessage(context,
"The date on this device is not synchronized with the server. Please adjust it to the correct date.",
"Date Out of Sync",
AppMessages.MESSAGE_INFO,
null);
}
}
}
protected static class AsyncCustomers extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... params) {
ArrayList<Customer> customers = null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetReferenceFiles((byte)4);
JSONParser parser = new JSONParser();
customers = parser.parseCustomer(jsonObj);
CustomersTable.importData(context, customers, this);
}
catch (NullPointerException e) {
}
catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
createProgress();
progress.setTitle("Downloading Customer Information");
}
@Override
protected void onPostExecute(Void result) {
new AsyncItems().execute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
progress.setMessage(values[0]);
}
public void showProgress(int value, int max) {
publishProgress(buildProgress(value, max));
}
}
protected static class AsyncItems extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... params) {
ArrayList<Item> items = null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetReferenceFiles((byte)6);
JSONParser parser = new JSONParser();
items = parser.parseItem(jsonObj);
ItemsTable.importData(context, items, this);
}
catch (NullPointerException e) {
}
catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
createProgress();
progress.setTitle("Downloading Items Master File");
}
@Override
protected void onPostExecute(Void result) {
if (progress != null) {
progress.dismis();
}
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
progress.setMessage(values[0]);
}
public void showProgress(int value, int max) {
publishProgress(buildProgress(value, max));
}
}
}
CustomerTable类(单独的文件)
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
public class CustomersTable {
public static void importData(Context context, ArrayList<Customer> customers, ReferenceFilesDownloader.AsyncCustomers async) {
ADIDBContext dbContext = new ADIDBContext(context);
String query = "DELETE FROM Customers";
dbContext.execSQL(query);
try {
dbContext.beginTransaction();
int row = 0;
for (Customer customer : customers) {
ContentValues values = new ContentValues();
async.showProgress(++row, customers.size());
values.put("CustomerId", customer.customerId);
values.put("LastName", customer.lastName);
values.put("FirstName", customer.firstName);
values.put("MiddleName", customer.middleName);
values.put("Address1", customer.address1);
values.put("Address2", customer.address2);
values.put("ProvinceId", customer.provinceId);
values.put("CityId", customer.cityId);
values.put("BarangayId", customer.barangayId);
dbContext.getDatabase().insert("Customers", null, values);
}
dbContext.setTransactionSuccessful();
}
catch (Exception ex) {
}
dbContext.endTransaction();
dbContext.close();
}
}
ItemTable类(单独的文件)
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
public class ItemsTable {
public static void importData(Context context, ArrayList<Item> items, ReferenceFilesDownloader.AsyncItems async) {
ADIDBContext dbContext = new ADIDBContext(context);
String query = "DELETE FROM Items";
dbContext.execSQL(query);
try {
dbContext.beginTransaction();
int row = 0;
for (Item item : items) {
ContentValues values = new ContentValues();
async.showProgress(++row, items.size());
values.put("Barcode", item.barcode);
values.put("ItemId", item.itemId);
values.put("ItemDesc", item.itemDesc);
values.put("UnitId", item.unitId);
values.put("CompanyId", item.companyId);
values.put("UnitDescription", item.unitDescription);
values.put("UnitConversion", item.unitConversion);
values.put("Cost", item.cost);
values.put("SellingPrice1", item.sellingPrice1);
values.put("SellingPrice2", item.sellingPrice2);
values.put("SellingPrice3", item.sellingPrice3);
values.put("SellingPrice4", item.sellingPrice4);
values.put("SellingPrice5", item.sellingPrice5);
values.put("PiecePrice1", item.piecePrice1);
values.put("PiecePrice2", item.piecePrice2);
values.put("PiecePrice3", item.piecePrice3);
values.put("PiecePrice4", item.piecePrice4);
values.put("PiecePrice5", item.piecePrice5);
values.put("Taxable", item.taxable);
dbContext.getDatabase().insert("Items", null, values);
}
dbContext.setTransactionSuccessful();
}
catch (Exception ex) {
}
dbContext.endTransaction();
dbContext.close();
}
}
1 回答
如果我没有错,你正在尝试处理导致异常的方向更改 .
SOLUTION 1: Prevent the Activity from being recreated
将此属性添加到您的活动清单中,
它交给您的
onConfigurationChanged()
方法,除了重新测量布局之外什么都不做 . 这应该解决旋转期间的问题 .SOLUTION 2: Lock the screen orientation
为您的活动定义固定方向,这应该可以解决问题 .
SOLUTION 3: Temporarily lock the screen in onPreExecute(), and unlock it in onPostExecute()
这是处理方向的棘手方法 . 只需在AsyncTask即将开始时锁定方向,然后在任务完成时解锁方向 . 看例子,