这是我的onPostExecute()方法
@Override
protected void onPostExecute(Void unused) {
TextView tvStatus=(TextView) layoutSendDialog.findViewById(R.id.tvPupukSendStatus);
if (bNodata){
tvStatus.setText("No data to be sent!!!");
}else {
if (bError && stopResend<5){
tvStatus.setText("Gagal terkirim di record #"+String.format("%d",recordCount)+" || ReSend : "+String.format("%d",stopResend)+" Kali ");
//SystemClock.sleep(10000);
//for (int i=1; i<=2; i++){
final AlertDialog dlg = createDialogFail();
dlg.show();
//
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the dialog
cursorSend=cDBPupuk.getNotSentRecords();
if (cursorSend!=null){
showDialog(CGeneral.DIALOG_SEND);
myAsyncTaskPupuk=new MyAsyncTaskPupuk();
myAsyncTaskPupuk.execute();
}
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 5000);
}
else if(bError && stopResend>=5){
myAsyncTaskPupuk.onCancelled();
tvStatus.setText("Gagal terkirim di record #"+String.format("%d",recordCount)+" || ReSend : "+String.format("%d",stopResend)+" Kali ");
CUtilities.showAlert(CInputHamaSend.this, "Koneksi GPRS Anda bermasalah atau terlalu lambat");
stopResend=0;//ulang dari 0 lagi
}
else {
tvStatus.setText("Sending Data : Finished");
//CUtilities.showAlert(CInputHamaSend.this, "Data Terkirim");
AlertDialog dlg = createDialogSend2();
dlg.show();
// Closing dashboard screen
//finish();
}
}
// dismissDialog(CGeneral.DIALOG_SEND);
}
这是我的对话
private AlertDialog createDialogFail(){
AlertDialog.Builder builder = new AlertDialog.Builder(CInputHamaSend.this);
builder.setMessage("Data Gagal terkirim ke server. Resend otomatis setelah 10 detik");
builder.setTitle("Fail");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
myAsyncTaskPupuk.cancel(true);
}
});
return builder.create();
}//createDialogFail
我有自动关闭对话框和每5秒钟运行asynctask的计时器。
如果是bError,则显示带有取消肯定按钮并运行myAsyncTaskPupuk.cancel(true);
public void onClick(DialogInterface dlg, int sumthin) {
myAsyncTaskPupuk.cancel(true);
}
});
但不行。
当我点击按钮警告对话框时,asynctask无法停止,仍在运行。
如何解决这个问题?如何使用alertdialog取消或停止我的asynctask?
编辑:: 我用
else if(bError && stopResend>=5){
myAsyncTaskPupuk.onCancelled();
tvStatus.setText("Gagal terkirim di record #"+String.format("%d",recordCount)+" || ReSend : "+String.format("%d",stopResend)+" Kali ");
CUtilities.showAlert(CInputHamaSend.this, "Koneksi GPRS Anda bermasalah atau terlalu lambat");
stopResend=0;//ulang dari 0 lagi
}
停止asynctask 5次并且它可以工作但如何在警告对话框中添加它?所以当我点击按钮时,asynctask停止了?
编辑:: 完整代码Asynctask
private class MyAsyncTaskPupuk extends AsyncTask<Void,Object ,Void> {
boolean bNodata=false;
boolean bError=false;
@Override
protected Void doInBackground(Void... arg0) {
bNodata=false;
bError=false;
recordCount=cursorSend.getCount();
if (recordCount<=0){//
bNodata=true;
return null;
}
cursorSend.moveToLast();
publishProgress(0,"Sending data started");
//SystemClock.sleep(1000);
CHamaRecord rec=new CHamaRecord();
for (int i=0; i<recordCount; i++){
if (isCancelled()) break;
if (i==1)break;
rec.lID=cursorSend.getLong(0);
rec.dLongitude=cursorSend.getDouble(1);
rec.dLatitude=cursorSend.getDouble(2);
rec.dAccuracy=cursorSend.getDouble(3);
rec.sFilename=cursorSend.getString(4);
rec.nUserId=cursorSend.getInt(5);
rec.nRate=cursorSend.getInt(6);
rec.lDate=cursorSend.getLong(7);
rec.sSent=cursorSend.getString(8);
rec.IDSite=cursorSend.getString(9);
rec.alamatSite=cursorSend.getString(10);
rec.komoditas=cursorSend.getString(11);
rec.luasSite=cursorSend.getString(12);
rec.petugas=cursorSend.getString(13);
rec.jnsHama=cursorSend.getString(14);
rec.jmlHama=cursorSend.getString(15);
rec.sn=cursorSend.getString(16);
rec.pn=cursorSend.getString(17);
rec.manufaktur=cursorSend.getString(18);
rec.lblHama=cursorSend.getString(19);
rec.lblKomoditas=cursorSend.getString(20);
rec.lblPetugas=cursorSend.getString(21);
publishProgress(1,i,rec);
if (!SendDataFoto(rec)){
recordCount=i;
bError=true;
stopResend=stopResend+1;
break;
}
else {
//change flag sent
rec.sSent=CGeneral.strSent;
cDBPupuk.updateEntry(rec.lID, rec);
}
// SystemClock.sleep(1000);
cursorSend.moveToNext();
}
return null;
}//doInBackground
private boolean SendDataFoto(CHamaRecord rec){
String slon=String.format("%f", rec.dLongitude);
String slat=String.format("%f", rec.dLatitude);
String sacc=String.format("%f", rec.dAccuracy);
String srate=String.format("%d",rec.nRate);
String sid=String.format("%d",rec.nUserId);
String ids=String.format(rec.IDSite);
String alt=String.format(rec.alamatSite);
String kmd=String.format(rec.komoditas);
String ls=String.format(rec.luasSite);
String op=String.format(rec.petugas);
String jns=String.format(rec.jnsHama);
String jml=String.format(rec.jmlHama);
String sn=String.format(rec.sn);
String pn=String.format(rec.pn);
String mFact=String.format(rec.manufaktur);
String lblhama=String.format(rec.lblHama);
String lblKomoditas=String.format(rec.lblKomoditas);
File file=new File(rec.sFilename);
String sfname=file.getName();
String cfname=file.getName();
int i=0;
String lfname=rec.sFilename;
sfname = sfname.substring(0, sfname.lastIndexOf("."));
Calendar cal=Calendar.getInstance();
cal.setTime(new Date(rec.lDate));
String sdat=CUtilities.DateToString(cal);
String url;
String spupuk;
if (CGeneral.nPupukOrPelihara==CGeneral.ACTIVITY_FOR_PUPUK){
url = CGlobalConfig.getURLRcvrPupuk();
spupuk="Hama";
}
else{
url = CGlobalConfig.getURLRcvrPeliharaImage();
spupuk="pelihara";
}
Bitmap bmp=BitmapFactory.decodeFile(lfname);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
HttpEntity entity=null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ByteArrayBody bab = new ByteArrayBody(ba, spupuk+"_"+cfname);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);
reqEntity.addPart("category", new StringBody(spupuk));
reqEntity.addPart("file_name", new StringBody(spupuk+"_"+cfname));
reqEntity.addPart("rate", new StringBody(srate));
reqEntity.addPart("tgl", new StringBody(sdat));
reqEntity.addPart("user_id", new StringBody(sid));
reqEntity.addPart("latitude", new StringBody(slat));
reqEntity.addPart("longitude", new StringBody(slon));
reqEntity.addPart("accuracy", new StringBody(sacc));
reqEntity.addPart("id_site", new StringBody(ids));
reqEntity.addPart("alamat_site", new StringBody(alt));
reqEntity.addPart("komoditas", new StringBody(kmd));
reqEntity.addPart("luas_area", new StringBody(ls));
reqEntity.addPart("petugas", new StringBody(op));
reqEntity.addPart("jenis_hama", new StringBody(jns));
reqEntity.addPart("jumlah_hama", new StringBody(jml));
reqEntity.addPart("serial", new StringBody(sn));
reqEntity.addPart("p_number", new StringBody(pn));
reqEntity.addPart("manufaktur", new StringBody(mFact));
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
//}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
String temp = null;
try {
if(entity == null){
publishProgress(0,"Send Fail");
SystemClock.sleep(500);
return false;
}
else{
temp = EntityUtils.toString(entity);
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (temp.compareTo("SUCCESS") == 0) {
publishProgress(0,"Send Ok");
SystemClock.sleep(500);
return true;
}
else{
publishProgress(0,"Send Fail");
return false;
}
}
@Override
protected void onProgressUpdate(Object... arg) {
Integer oi=(Integer)arg[0];
String oStr;
CHamaRecord rec;
int flag=oi.intValue();
int nVal;
String str;
TextView tvStatus=(TextView) layoutSendDialog.findViewById(R.id.tvPupukSendStatus);
TextView tview;
switch (flag) {
case 0 :
oStr=(String)arg[1];
tvStatus.setText(oStr);
break;
case 1 :
oi=(Integer)arg[1];
rec=(CHamaRecord)arg[2];
nVal=oi.intValue();
str="Send record #"+String.format("%d",nVal);
tvStatus.setText(str);
str=String.format("%d", rec.lID);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendID);
tview.setText(str);
str=String.format(rec.IDSite);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendIDSite);
tview.setText(str);
str=String.format(rec.alamatSite);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendAlamat);
tview.setText(str);
str=String.format(rec.lblKomoditas);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendKomoditas);
tview.setText(str);
str=String.format(rec.luasSite);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendLuas);
tview.setText(str);
str=String.format(rec.lblPetugas);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendPetugas);
tview.setText(str);
str=String.format(rec.lblHama);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendJenis);
tview.setText(str);
str=String.format(rec.jmlHama);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendJumlah);
tview.setText(str);
str=String.format(rec.sn);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendSerial);
tview.setText(str);
str=String.format(rec.pn);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendProduk);
tview.setText(str);
str=String.format(rec.manufaktur);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendManufaktur);
tview.setText(str);
str=String.format("%+3.5f", rec.dLongitude);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendLongitude);
tview.setText(str);
str=String.format("%+3.5f", rec.dLatitude);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendLatitude);
tview.setText(str);
/*str=String.format("%2.2f", rec.dAccuracy);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendAccuracy);
tview.setText(str);*/
Date dt=new Date(rec.lDate);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendDate);
tview.setText(dt.toLocaleString());
/*str=String.format("%d", rec.nRate);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendRating);
tview.setText(str);
str=String.format("%d", rec.nUserId);
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendOperator);
tview.setText(str); */
File file=new File(rec.sFilename);
String fname=file.getName();
tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendFilename);
tview.setText(fname);
break;
}
}
//
@Override
protected void onPostExecute(Void unused) {
TextView tvStatus=(TextView) layoutSendDialog.findViewById(R.id.tvPupukSendStatus);
if (bNodata){
tvStatus.setText("No data to be sent!!!");
}else {
if (bError && stopResend<5){
tvStatus.setText("Gagal terkirim di record #"+String.format("%d",recordCount)+" || ReSend : "+String.format("%d",stopResend)+" Kali ");
//SystemClock.sleep(10000);
//for (int i=1; i<=2; i++){
final AlertDialog dlg = createDialogFail();
dlg.show();
//
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the dialog
cursorSend=cDBPupuk.getNotSentRecords();
if (cursorSend!=null){
showDialog(CGeneral.DIALOG_SEND);
myAsyncTaskPupuk=new MyAsyncTaskPupuk();
myAsyncTaskPupuk.execute();
}
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 5000);
}
else if(bError && stopResend>=5){
myAsyncTaskPupuk.onCancelled();
tvStatus.setText("Gagal terkirim di record #"+String.format("%d",recordCount)+" || ReSend : "+String.format("%d",stopResend)+" Kali ");
CUtilities.showAlert(CInputHamaSend.this, "Koneksi GPRS Anda bermasalah atau terlalu lambat");
stopResend=0;//ulang dari 0 lagi
}
else {
tvStatus.setText("Sending Data : Finished");
//CUtilities.showAlert(CInputHamaSend.this, "Data Terkirim");
AlertDialog dlg = createDialogSend2();
dlg.show();
// Closing dashboard screen
//finish();
}
}
// dismissDialog(CGeneral.DIALOG_SEND);
}
protected void onCancelled(Void unused) {
dismissDialog(CGeneral.DIALOG_SEND);
}
}// end asynctask
BR
亚历