0

我正在开发向 Number 发送短信的 APP,如果 SMS 未能执行 Asynctask 并在间隔后检查以再次重新发送短信,但是,我所有的工作都浪费了,因为我不明白 Asynctask这里是我的代码。

异步类

        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;
        }
        };

短信发送代码及错误处理

        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));

问题: 任务开始但任务保持活动状态并在 10 秒后重复发送短信我也已取消但 asyntask 在成功发送短信后不取消

由于这个问题,请帮助我没有睡一夜:(

问候

4

1 回答 1

0

这种情况会创建一个立即取消的新异步任务。

case Activity.RESULT_OK:
    //sms sent if bol true cancel the Asynctask :)
    if(bol){
        new checkList().cancel(true);
    }
    break;

要取消 AsyncTask,您需要将其存储在变量中,例如

checkList smsTask = new checkList();
smsTask.execute();

// Other app logic

// Replacing the internal portion of that case is the new cancel code
if (bol) {
    smsTask.cancel(true);
}
于 2012-08-09T12:28:12.137 回答