i am developing APP which send sms to Number, if SMS failed the Asynctask execute and check after interval to resend sms again but, all my work wasted because i don’t understand the Asynctask here is my Code.
ASYNC Class
class checkList extends AsyncTask<String, Void, Void> {
public Void doInBackground(String... p) {
while (true) {
already_running_async=true;
sms.sendTextMessage(phone_nr, null, "SmS Sending", sentPI, null);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isCancelled()) break;
}
return null;
}
};
SMS sending Code and Error Handling
bol=false;
already_running_async=false;
check=false;
sms = SmsManager.getDefault();
if(!phone_nr.equals(""))
sms.sendTextMessage(phone_nr, null,"Sms body" , sentPI, null);
sendBroadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode())
{
case Activity.RESULT_OK:
//sms sent if bol true cancel the Asynctask :)
if(bol){
new checkList().cancel(true);}
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
if(already_running_async==false){
new checkList().execute();
bol=true;}
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
if(already_running_async==false){
new checkList().execute();
bol=true;}
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
if(already_running_async==false){
new checkList().execute();
bol=true;}
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
if(already_running_async==false){
new checkList().execute();
bol=true;}
break;
}
}
};
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));
Problem:
task starts but task remain alive and send sms repeatedly after 10 second i have also put the cancel but asyntask doesnot cancel after successfull sms is sent
Please Help i havent Slept for Night because of this problem 🙁
Regards
This case creates a new asynctask that is immediately canceled.
To cancel the AsyncTask you need to store it in a variable, like