杀Android的所有的AsyncTask任务 [英] Kill All Asynctask tasks in Android

查看:114
本文介绍了杀Android的所有的AsyncTask任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing a socket based app. I need to get the data from the Server socket and display to listview for every second.

我是从我的服务使用报警管理这样发送的广播事件......

I an sending the broadcast event from my service using Alarm Manager like this...

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

和活动中,我越来越喜欢

and in the activity, I am getting like

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

                   new RetriveStock().execute();

                }

            } catch (Exception e) {
            }

        }

    }

其中RetriveStock是异步任务。

where RetriveStock is the Async task.

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没有更新,直到previous异步任务是在旧的屏幕完成。

I am reading the data and displaying to listview very first time activity is created. when I navigate to some other screen,UI is not updating until the previous Async tasks are completed in the old screen.

我想导航到新屏幕前杀死/所有的异步任务。如何杀死所有的异步任务。

I want to kill the all the Async tasks on/before navigating to new screen. how to kill the all the async tasks.

请帮忙,
谢谢!

Please help, Thanks!!!

推荐答案

您应该定期检查任务是通过调用取消 isCancelled() doInBackground 方法。要检查它会定期您必须使用doInBackground循环

You should periodically check if the task is cancelled by calling isCancelled() in doInBackground method. To check it periodically you have to use a loop in 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;
    }

这篇关于杀Android的所有的AsyncTask任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆