杀死Android中的所有Asynctask任务

时间:2014-04-16 15:01:02

标签: android sockets android-asynctask

我正在开发一个基于套接字的应用程序。我需要从服务器套接字获取数据并每秒显示到listview。

我使用闹钟管理器从我的服务发送广播事件......

   @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    fireAlarm();

    return START_NOT_STICKY;

}
public void fireAlarm() {
    /**
     * call broadcost reciver for AlarmReceiver
     */
    //Intent intent = new Intent(AlarmService.this.getApplicationContext(), DefaultMarketWatch.class);
    Intent intent=new Intent();
    intent.setAction("com.pgi.eaxample");
     pendingIntent = PendingIntent
            .getBroadcast(AlarmService.this.getApplicationContext(), 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
     alarm = (AlarmManager) AlarmService.this.getApplicationContext()
            .getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pendingIntent);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000, pendingIntent);


    sendBroadcast(intent);
}

在活动中,我变得像

@Override
    public void onReceive(Context context, Intent intent) {

                   new RetriveStock().execute();

                }

            } catch (Exception e) {
            }

        }

    }

其中RetriveStock是异步任务。

public class RetriveStock extends AsyncTask<Void, Void, ArrayList<User>> {

    @Override
    protected ArrayList<User> doInBackground(Void... params) {
        isCycleQuit=false;
        JSONmessage += client.clientReceive(1);
        message=JSONmessage;
        JSONmessage="";
        System.out.println("MESSAGE Socket::" + message);

        return null;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    protected void onPostExecute(ArrayList<User> result) {
        if (!message.contains("null")) {
            printJson();
            // updateList();
            displayView();
        }
        tasiDisplay();

        if (message.contains("AlertStatus:")) {
            String arrayMessage[] = message.split("AlertStatus:");
            String arrayMessage2[] = arrayMessage[1].split(";");// AlertStatus:10,ALertCheck;
            String arrayMessage3[] = arrayMessage2[0].split(",");
            sqladapter.insertAlertStatus(arrayMessage3[1],
                    Integer.parseInt(arrayMessage3[0]));
            // message = "AlertExecuted:" + arrayMessage3[0];
        }
        if (message.contains("AlertExecuted:")) {
            progress.dismiss();
            String arrayMessage[] = message.split("AlertExecuted:");// AlertExecuted:10;
            String arrayMessage2[] = arrayMessage[1].split(";");
            final String alertMessage = arrayMessage2[0];

            if (sqladapter.checkAlertExist(Integer.parseInt(alertMessage)))
                alertExecute.displayAlert(alertMessage,
                        DefaultMarketWatch.this);
            message = message.replaceAll("AlertExecuted:", "");
        }
        listSetAdapter();
        isCycleQuit=true;
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // mProgressDialog.setProgress(values[0]);
        super.onProgressUpdate(values);
    }

}
public void printJson() {
    String str = "";

    while (message.contains("{") && message.contains("}")) {

        System.out.println("printJson::"+message);
        try {
            String splitString = message.substring(message.indexOf('{'),
                    message.indexOf('}') + 1);
            for (int i = value; i < symbolList.size(); i++) {
                String selectedSymbol = symbolList.get(i);
                String cotes = "\"Id\":";
                if (splitString.contains(cotes + selectedSymbol + ",")) {
                    try {
                        // JSONArray jsonArray = new JSONArray(str);

                        // for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject json = new JSONObject(splitString);

                        if (marketWatch.equalsIgnoreCase("custom"))
                            value = 0;
                        else
                            value = 1;
                        String symbol = json.getString("Symbol_En");
                        double high = Double.parseDouble(json
                                .getString("High"));
                        double low = Double.parseDouble(json
                                .getString("Low"));
                        User obj = new User();
                        boolean checkSymbol = false;
                        for (int j = 0; j < list.size(); j++) {
                            obj = list.get(j);
                            if (obj.getSymbol().equalsIgnoreCase(symbol)) {
                                checkSymbol = true;
                                break;
                            }
                        }
                        if (!checkSymbol) {
                            obj = new User();
                            obj.Symbol_En = json.getString("Symbol_En");
                            obj.Symbol_Ar = json.getString("Symbol_Ar");
                            obj.AskPrice = json.getString("Ask");
                            obj.BidPrice = json.getString("Bid");
                            obj.AskQuantity = json.getString("AskQuantity");
                            obj.High = high + "";
                            obj.Low = low + "";
                            obj.Open = json.getString("Open");
                            obj.Close = json.getString("Close");
                            obj.PerChange = json.getString("PerChange");
                            obj.NetChange = json.getString("NetChange");
                            obj.Volume = json.getString("Volume");
                            obj.Ltp = json.getString("LTP");
                            obj.TimeStamp = json.getString("TimeStamp");
                            obj.symbolId = json.getString("Id");
                            changePer = obj.PerChange;
                            netChange = obj.NetChange;
                            volume = obj.Volume;
                            open = obj.Open;
                            askQuality = obj.AskQuantity;
                            ltp = obj.Ltp;
                            if (obj.symbolId.equalsIgnoreCase("1001")) {

                                try {
                                    String change;
                                    double value;
                                    String tasiValueSub[];
                                    value = Double.parseDouble(changePer);
                                    change = String.format("%.2f", value);
                                    if (change.equalsIgnoreCase("0.00"))
                                        tasi_perchange = "0";
                                    else
                                        tasi_perchange = change;
                                    value = Double.parseDouble(netChange);
                                    change = String.format("%.2f", value);
                                    if (change.equalsIgnoreCase("0.00"))
                                        tasi_netChange = "0";
                                    else
                                        tasi_netChange = change;
                                    tasi_volume = addCamas(volume);
                                    value = Double.parseDouble(open);
                                    change = String.format("%.2f", value);
                                    if (change.equalsIgnoreCase("0.00"))
                                        tasi_index = "0";
                                    else {
                                        tasiValueSub = change.split("\\.");
                                        tasiValueSub[0] = addCamas(tasiValueSub[0]);
                                        tasi_index = tasiValueSub[0] + "."
                                                + tasiValueSub[1];
                                    }
                                    // tasi_index = change;

                                    tasi_noOfTrads = addCamas(askQuality);
                                    NumberFormat formatter = new DecimalFormat(
                                            "#0.00");
                                    tasi_value = formatter.format(Double
                                            .parseDouble(ltp)) + "";
                                    if (tasi_value.equalsIgnoreCase("0.00"))
                                        tasi_value = "0";
                                    else {
                                        tasiValueSub = tasi_value
                                                .split("\\.");
                                        tasiValueSub[0] = addCamas(tasiValueSub[0]);
                                        tasi_value = tasiValueSub[0] + "."
                                                + tasiValueSub[1];
                                    }
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                } catch (IllegalStateException e) {
                                }
                            } else {
                                list.add(obj);
                            }
                        } else {

                            obj.Symbol_En = json.getString("Symbol_En");
                            obj.AskPrice = json.getString("Ask");
                            obj.BidPrice = json.getString("Bid");
                            obj.High = high + "";
                            obj.Low = low + "";
                            obj.Open = json.getString("Open");
                            obj.Close = json.getString("Close");
                            obj.PerChange = json.getString("PerChange");
                            obj.NetChange = json.getString("NetChange");
                            obj.Volume = json.getString("Volume");
                            obj.Ltp = json.getString("LTP");
                            obj.TimeStamp = json.getString("TimeStamp");
                            obj.symbolId = json.getString("Id");
                            changePer = obj.PerChange;
                            netChange = obj.NetChange;
                            volume = obj.Open;
                            open = obj.Open;
                            askQuality = obj.AskQuantity;
                            ltp = obj.Ltp;
                        }

                        // }
                    } catch (JSONException e1) {
                        // ////System.out.println("///////////////////////"
                        // +
                        // e1);
                        log.createFile(str);
                        e1.printStackTrace();
                    } catch (NumberFormatException e) {
                        log.createFile(str);
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        log.createFile(str);
                        e.printStackTrace();
                    }
                    // str = str + splitString;
                }
            }
            if(message.indexOf('}')>0){
                message = message.substring(message.indexOf('}') + 1);
            }

        } catch (StringIndexOutOfBoundsException e) {
            String errMsg = e.getClass().getName() + " " + e.getMessage();
            log.createFile("Error in printJson" + errMsg + "\n");
            e.printStackTrace();
        } catch (Exception e) {
            String errMsg = e.getClass().getName() + " " + e.getMessage();
            log.createFile("Error in printJson" + errMsg + "\n");
            e.printStackTrace();
        }
    }
    // ////System.out.println("Message:" + message);
    // message = str;
    // if (!str.equalsIgnoreCase("")) {
    // str = str.replace("}", "},");
    // if ((str.charAt(str.length() - 1) == ',')) {
    // str = str.substring(0, str.length() - 1);
    //
    // }
    // }
    // str = "[" + str + "]";

    // ////System.out.println("STR VALUE:" + str);

}

我正在读取数据并在第一次创建活动时显示到listview。 当我导航到其他屏幕时,在旧屏幕中完成之前的异步任务之前,UI不会更新。

我希望在导航到新屏幕之前/之后终止所有异步任务。如何杀死所有异步任务。

请帮忙, 感谢!!!

2 个答案:

答案 0 :(得分:0)

将Async任务存储在数组中。并在需要时停止:

//Array of task
ArrayList<AsyncTask> asyntask= new ArrayList<>();

//Add task to your array
asyntask.add(new RetriveStock().execute());

//Stop task
for (RetriveStock task : asyntask){
    task.cancel(true);
}

答案 1 :(得分:0)

您应该通过isCancelled()方法调用doInBackground来定期检查任务是否已取消。要定期检查,您必须在doInBackground中使用循环

 @Override
    protected ArrayList<User> doInBackground(Void... params) {


        while(clientHasNext()) { // I just made it up

            if(isCancelled()) {
                return null; 
            }

            isCycleQuit=false;
            JSONmessage += client.clientReceive(1);
            message=JSONmessage;
            JSONmessage="";
            System.out.println("MESSAGE Socket::" + message);   

        }

        return null;
    }