2015-05-09 150 views
0

我正在使用AsyncTask來執行後臺任務。任務處於一個while循環中。 如果後臺任務仍在運行,我如何更新我的UI,因爲後期執行劑量不工作。從後臺任務中更新android UI

感謝

保護字符串doInBackground(虛空...... PARAMS){

 while(true){ 


     Log.i(LOG_TAG, "Executing Background Task"); 
     try{ 


      String dataFromBT = btc.getData(); 
      Log.i(LOG_TAG, "BT Data: "+dataFromBT); 
      if(dataFromBT.contains("B1")){ 
       dataFromBT = "Warning Message 1"; 

      } 
      if(dataFromBT.contains("B2")) 
      { 
       dataFromBT="Warning Message 2"; 
      } 

      if(dataFromBT.contains("B3")){ 

       dataFromBT="Warning Message 3"; 
      } 

      if(dataFromBT.contains("B4")){ 

       dataFromBT="Warning Message 4"; 
      } 

      if (groupOwnerAddress!=null) { 


       Log.i(LOG_TAG, "Info is not null mobiles connected"); 



       // This is the server side 
       if (isthisthegrpowner == true) { 

        Log.w(LOG_TAG, "Group Owner: I am the Group Owner "); 

        Log.w(LOG_TAG, "Group Owner: Opening a Server Socket"); 
        ServerSocket serverSocket; 
        serverSocket = new ServerSocket(8988); 
        Log.w(LOG_TAG, "Group Owner: Server Socket Opened, waiting for PEER"); 

        Socket client = serverSocket.accept(); 
        Log.w(LOG_TAG, "Group Owner: Server Connection Done"); 
        serverSocket.setReuseAddress(true); 

        try{ 

          // Get client IP from Socket 
          clientipadd = client.getRemoteSocketAddress(); 
          clientport = client.getPort(); 
          String clientip = clientipadd.toString(); 
          Log.w(LOG_TAG, "Group Owner: Client IP from socket found: " + clientip); 


          Log.w(LOG_TAG, "Group Owner: Input Stream Started"); 
          InputStream inputstream = client.getInputStream(); 
          ByteArrayOutputStream byteArrayOutputStream = 
            new ByteArrayOutputStream(1024); 
          byte[] buffer = new byte[1024]; 

          String response = ""; 

          int bytesRead; 
          while ((bytesRead = inputstream.read(buffer)) != -1){ 
            byteArrayOutputStream.write(buffer, 0, bytesRead); 
            response += byteArrayOutputStream.toString("UTF-8"); 
          } 


          // Split the string sent from the client and add it to the HashMap 
          String input = response; 
          final String[] splitStringArray = input.split(" "); 
          String a = splitStringArray[0]; 
          String b = splitStringArray[1]; 
          String c = splitStringArray[2]; 
          String d = splitStringArray[3]; 
          String e = splitStringArray[4]; 
          Log.w(LOG_TAG, "Group Owner: Response from client split: " + " 1: " + a + " 2: "+ b + " 3:" + c + " 4: " + d + " 5: " + e); 

          data.put(clientip, new VehicleInfoEntry(a, b , c));  
          client.shutdownInput(); 


          Log.w(LOG_TAG, "Group Owner: Reply from Peer: " + response); 

        }finally{ 

         Log.w(LOG_TAG, "Group Owner: Output Stream started"); 
         OutputStream stream = client.getOutputStream(); 
         PrintStream printStream = new PrintStream(stream); 
         printStream.print("hello hellomac hellodata" + Latitude + " " + Longitude + dataFromBT); 
         Log.w(LOG_TAG, "Group Owner: Output Stream finished"); 

         serverSocket.close(); 
         Log.w(LOG_TAG, "Group Owner: Socket Closed"); 
        } 

        // This is the client side 
        } else{ 

        Log.w(LOG_TAG, "PEER: I am a PEER"); 
        InetAddress ownerAdd = groupOwnerAddress; 
        int ownerPort = 8988; 
        Socket server = new Socket(); 
        try { 


         server.connect((new InetSocketAddress(ownerAdd, ownerPort))); 
         Log.w(LOG_TAG, "PEER: Socket done "); 

         Log.w(LOG_TAG, "PEER: Output Stream Started "); 
         OutputStream stream = server.getOutputStream(); 
         PrintStream printStream = new PrintStream(stream); 
         printStream.print("hello hellomac hellodata" + " " + Latitude + " " + Longitude + dataFromBT); 

         Log.w(LOG_TAG, "PEER: Output Stream Done"); 

         server.shutdownOutput(); 
         // printStream.close(); 
        } finally { 

         Log.w(LOG_TAG, "PEER: Input Stream Started"); 

         InputStream inputstream = server.getInputStream(); 
         ByteArrayOutputStream byteArrayOutputStream = 
           new ByteArrayOutputStream(1024); 
         byte[] buffer = new byte[1024]; 

         String response = ""; 

         int bytesRead; 
         while ((bytesRead = inputstream.read(buffer)) != -1){ 
           byteArrayOutputStream.write(buffer, 0, bytesRead); 
           response += byteArrayOutputStream.toString("UTF-8"); 

           Log.w(LOG_TAG, "PEER: Reply from Group Owner: " + response); 

           server.close(); 
           Log.w(LOG_TAG, "PEER: Server socket closed"); 

         } 

        } 

        } 
       } 

       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       }finally { 


       }try { 

        Thread.sleep(2000); // changed to 5000 for other peer 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 





      } 



    } 
+0

使用BroadcastReceiver遵循鏈接:http://stackoverflow.com/questions/14695537/android-update-activity-ui-from-service –

回答

1

如果您想使用後臺線程的UI則在下面使用runOnUiThreaddoInBackground

runOnUiThread(new Runnable(){ 
     public void run() { 
      // update UI 
     } 
+0

嗨,感謝您的幫助!我一直在試圖做到這一點,我沒有得到它的工作....我應該把runOnUiThread在doInBackground? – Lissiel

+0

是的,我提到它在回答你必須在doInbackground中使用它 –

+0

OMG IT的作品! :D非常感謝你! :d – Lissiel

1

使用publishProgress方法。任何你在做onProgressUpdate後 publishProgress(進度UI線程

private class TestAsyncTask extends AsyncTask<Void, String, Void> { 
     @Override 
     protected Void doInBackground(Void... voids) { 
      SystemClock.sleep(1000); 
      publishProgress("Test"); 
      SystemClock.sleep(1000); 
      return null; 
     } 

     @Override 
     protected void onProgressUpdate(String... values) { 
      String test = values[0]; 
      // Do something with it 
     } 
    } 

保護無效onProgressUpdate(進展...值)

在API級別的UI線程上運行3次上運行...)被調用。指定的值是傳遞給publishProgress(Progress ...)的 值。

參數值指示進度的值。