2014-04-16 4 views
0

소켓 기반 앱을 개발 중입니다. 서버 소켓에서 데이터를 가져와 매초마다 listview에 표시해야합니다.Android에서 Asynctask 작업을 모두 종료하십시오.

나는 ...이 같은 알람 관리자를 사용하여 내 서비스에서

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

을 방송 이벤트를 보내고 RetriveStock는 비동기 작업입니다 활동에, 나는

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

        new RetriveStock().execute(); 

       } 

      } catch (Exception e) { 
      } 

     } 

    } 

처럼 무엇입니까 .

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

} 

데이터를 읽고 목록보기에 처음으로 활동을 작성했습니다. 다른 화면으로 이동하면 이전 비동기 작업이 이전 화면에서 완료 될 때까지 UI가 업데이트되지 않습니다.

새 화면으로 이동하기 전에 모든 비동기 작업을 삭제하고 싶습니다. 모든 비동기 작업을 죽이는 방법.

도와주세요, 고마워요!

답변

0

비동기 작업을 배열에 저장하십시오. 그리고 당신이 원하는 경우이를 중지 : 작업이 doInBackground 방법에 isCancelled()를 호출하여 취소하는 경우가 주기적으로 확인해야

//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); 
} 
+0

안녕하세요 Neige, 빠른 응답 주셔서 감사합니다. 위의 트릭을 이미 사용했지만 도움이되지 않습니다. 다른 해결책. – user2085965

+0

도움이되지 않습니까? 어느면에서 도움이되지 않았습니까? 스레드가 멈추기를 거부 했습니까? 추락 했나요? 너무 느린? –

+0

RetriveStock의 소스 코드를 게시 할 수 있습니까? – Neige

0

. 정기적으로 확인하려면 doloBackground에 루프를 사용해야합니다 ().

@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; 
    } 
+1

을 찾으십시오. – njzk2

+0

당신 말이 맞아요. 나는 그것을 편집 할 것이다. –

+0

나는 그것을 시도 할 것이다. 하지만 clientHasNext() 메서드는 무엇입니까 – user2085965

관련 문제