在服务中重新启动AsyncTask

时间:2012-10-24 15:24:53

标签: android service android-asynctask broadcastreceiver

我有Service和AsyncTask,由于检查服务器上的更新。如果获得一些数据,它必须重新执行,如果没有,则必须重新执行。所以我的AsyncTask实现是:

 private class DklabExecute extends AsyncTask<Void, String, Void> {
            int count;

            Calendar calendar = Calendar.getInstance();
             java.util.Date now = calendar.getTime();
             java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
            String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
                      ",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());

            HttpGet rplPost = new HttpGet(url);

            protected Void doInBackground(Void... args) 
            {

                Log.i("service count", Integer.toString(count));
                count ++;
             Log.i("md5 func", md5(LoginActivity.passUserId)); 


                String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";

                 JSONParser  parser = new JSONParser();
                 DefaultHttpClient testClient = new DefaultHttpClient();
                 DefaultHttpClient rplClient = new DefaultHttpClient();

                try {

                     List<NameValuePair> params = new ArrayList<NameValuePair>();
                     params.add(new BasicNameValuePair("", ""));
                     HttpGet httpTest = new HttpGet(testData);

                     httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
                     rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());

                    try {



                        httpResponse = rplClient.execute(rplPost);
                    }

                     catch (ClientProtocolException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    Header[] head = httpResponse.getAllHeaders();
                    Log.i("http Response",httpResponse.toString());
                    for (Header one:head)
                    {
                        Log.i("headers",one.toString());
                    }
                    Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                            sb.append(line);// + "n");
                        }
                        try
                        {
                            is.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    json = sb.toString();
                    Log.i("rpl response",json);
                    if (new JSONArray(json) != null)
                        jArr = new JSONArray(json);
                    else
                        this.cancel(true);
                     JSONObject toObj = jArr.getJSONObject(0);
                     JSONObject data = toObj.getJSONObject(KEY_DATA);
                    if (data.has(KEY_ORDER))
                    {
                        for (Order a : ServiceMessages.orderExport)
                          {
                             Log.i("service before list", a.toString());
                          }
                         Log.i(" ", "  ");
                          for (Order a : DashboardActivityAlt.forPrint)
                          {

                             Log.i("before dashboard list", a.toString());
                          }
                        JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
                        Gson gson = new Gson();
                        Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
                        try
                        {
                            for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
                            {
                                Order a = itr.next();

                                Log.i("order count", a.toString());

                                if(orderObj.getOrderid()==a.getOrderid())
                                {
                                    Log.i("Service","order was changed");
                                    a = orderObj;
                                    someMethod("Your order  "+ orderObj.getTitle() + "  was changed");

                                }
                                else
                                {
                                    Log.i("Service","order"+ orderObj.getTitle()+" was added");
    //                              DashboardActivityAlt.forPrint.add(0, orderObj);
                                    ServiceMessages.orderExport.add(0,orderObj);
                                    Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
                                    someMethod("Your order  "+ orderObj.getTitle() + "  was added");
                                }

                            }
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        for (Order a : ServiceMessages.orderExport)
                          {

                             Log.i("service after list", a.toString());
                          }
                         Log.i(" ", "  ");
                          for (Order a : DashboardActivityAlt.forPrint)
                          {

                             Log.i("after dashboard list", a.toString());
                          }
//                      intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
                        sendBroadcast(intentOrder);
                        Log.i("after parse order",orderObj.toString());
                        Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
                    }
                    else if (data.has(KEY_MESSAGE))
                    {

                        JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
                        Gson gson = new Gson();
                        Log.i("messages before parse", jsonMessage.toString());
                        for (Order a: DashboardActivityAlt.forPrint)
                        {
                            Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
                        }
                        Log.i("disparse message",jsonMessage.toString());
                        Message message =  gson.fromJson(jsonMessage.toString(),Message.class);
                        Log.i("incomming message",message.toString());
                        JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
                        Threads thread =  gson.fromJson(jsonThread.toString(),Threads.class);
                        Log.i("incomming thread",thread.toString());
                        Order orderChanged = new Order();
                        String orderName = null;
                        for(Order as : DashboardActivityAlt.forPrint)
                        {

                            if (as.getOrderid() == thread.getTreadOrder().getOrderid())
                            {
                                orderName = as.getTitle();
                                orderChanged = as;
                                Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
                            }

                        }
                        Log.i("orderchanged",orderChanged.toString());
                        someMethod("Your order  "+ thread.getTreadOrder().getTitle() + "  was changed. Message was added");
                        orderChanged.getCusThread().addMessage(message);
                        sendBroadcast(intentMessage);
                        Log.i("messages service", "before sleep");

                        Log.i("messages service", "after sleep");

                    }
                    else

                    {

                        this.cancel(true);

                    }

                } 
                 catch (IllegalStateException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                } catch (IOException e2) {
                     rplClient.getConnectionManager().shutdown();
                     testClient.getConnectionManager().shutdown();
                     someMethod("You've lost internet connection. You should try later.");
                    e2.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 

                return null;
             }
            protected void onPostExecute(Void bitmap) {

                 this.cancel(true);
                 new DklabExecute().execute();
             }
        }

如果我将一些数据发送到服务器,它会通过rpl服务器以JSON格式返回给我。一切都运行良好,但问题是当我从服务器获取一些数据时,在onPostExecute()方法中重新执行了AsyncTask,并且在我的订单列表中重复了一两次数据。如果我不重新执行AsyncTask,则仅在onStartCommand()方法中进行监听,但不是永久性的。请告诉我如何以最佳方式实现这一点......

1 个答案:

答案 0 :(得分:1)

如果是服务,则没有理由使用AsyncTask。 构建AyncTasks是为了在原始线程(通常是UI线程)上传回内容,但服务没有这些内容。

我建议您使用ScheduledExecutorService而不是http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html

 private ScheduledExecutorService executor;

 // call those on startCommand
        executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);

并让Runnable完成工作

private Runnable run = new Runnable() {

      @Override
      public void run() {
              // do your network stuff
      }
};

并且不要忘记在服务停止时取消所有内容

   executor.shutdown();

编辑:

或者在循环中使用线程,你可以:

    boolean isRunning;

    // this on your start
    Thread t = new Thread(run);
    isRunning = true;
    t.start();

runnable

private Runnable run = new Runnable() {

      @Override
      public void run() {
              while(isRunning){
                    // do your network stuff
              }
      }
};

再次,不要忘记在服务结束时完成:

     isRunning = false;