2016-03-15 45 views
-4

這是我的代碼。當工作線程完成其工作在android

公共類MainActivity擴展AppCompatActivity {

private ListView listView; 

    // URL to get contacts JSON 
    private static String url = "example.com"; 

    // JSON Node names 
    private static final String TAG_DEVICES = "devices"; 
    private static final String TAG_TYPE = "type"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_MODEL = "model"; 

    // contacts JSONArray 
    JSONArray devices = null; 
    String jsonStr= null; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     listView = (ListView) findViewById(R.id.devices); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 


     /* 
     List<Device> devices = new ArrayList<>(); 

     Device device1 = new Device("tv", "la22c450e1", "samsung"); 
     Device device2 = new Device("washing machine", "lg34gfer", "lg"); 
     Device device3 = new Device("monitor", "dlrtio78", "dell"); 
     Device device4 = new Device("tv", "sie45vgt", "sansui"); 
     devices.add(device1); 
     devices.add(device2); 
     devices.add(device3); 
     devices.add(device4); 
    */ 


     List<Device> deviceList = new ArrayList<>(); 
     String jsonStr = null; 

     startProgress(url); 

     // ONCE GET NOTIFICATION FROM THREAD then run this code. 

     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       devices = jsonObj.getJSONArray(TAG_DEVICES); 

       // looping through All Contacts 
       for (int i = 0; i < devices.length(); i++) { 
        JSONObject c = devices.getJSONObject(i); 
        String name = c.getString(TAG_NAME); 
        String model = c.getString(TAG_MODEL); 
        String type = c.getString(TAG_TYPE); 
        Device device = new Device(type, model, name); 

        // adding device to device list 
        deviceList.add(device); 

       } 
       DeviceAdapter adapter = new DeviceAdapter(getApplicationContext(), deviceList); 
       listView.setAdapter(adapter); 


      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 
    } 

    private void startProgress(final String url) { 
     // do something long 
     Runnable runnable = new Runnable() { 
      @Override 
      public void run() { 

       try{ 
        jsonStr = FetchData(url); 
       } 
       catch(IOException ie) { 
        ie.printStackTrace(); 
       } 


      } 
     }; 
     new Thread(runnable).start(); 
    } 

    private String FetchData(String url) throws IOException { 
     URL obj = new URL(url); 
     StringBuffer stringBuffer = null; 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
     con.setRequestMethod("GET"); 
     //con.setRequestProperty("User-Agent", USER_AGENT); 
     int responseCode = con.getResponseCode(); 
     System.out.println("GET Response Code :: " + responseCode); 
     if (responseCode == HttpURLConnection.HTTP_OK) { // success 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        con.getInputStream())); 
      String inputLine; 
      stringBuffer = new StringBuffer(); 

      while ((inputLine = in.readLine()) != null) { 
       stringBuffer.append(inputLine); 
      } 
      in.close(); 

      // print result 
      System.out.println(stringBuffer.toString()); 
     } else { 
      System.out.println("GET request not worked"); 
     } 


     return stringBuffer.toString(); 

    } 
} 

如何,我應該得到通知這裏(//儘快尋求通知,然後線程運行這段代碼。)從工作線程只通知後執行的代碼?

編輯:我瞭解AsyncTask可以讓我的生活變得輕鬆。但由於需求描述我不能使用AsyncTask。所以請建議我最好的替代AsyncTask。

+2

回撥可以在這裏使用! –

+0

而不是使用線程,研究'AsyncTask',它更好地使用和管理'AsyncTask'。 –

+1

...回調的問題是它仍然會在工作線程上運行 - 所以你不能在那裏觸摸UI ...這就是爲什麼你需要發佈到主線程處理程序...然後AsyncTask更容易使用,因爲它已經實現這...解析JSON也是費時的,所以也應該在後臺線程上完成...仍然這樣的問題被問到bazillion時間 – Selvin

回答

0

這沒有任何意義:

startProgress(url); 
// ONCE GET NOTIFICATION FROM THREAD then run this code. 
... 

我猜想,「一旦得到線程的通知」的解釋是:等待其它線程。

開始一個新的線程,然後立即等待它完成是沒有任何意義的。多線程的要點是兩個(或更多)線程可以在同一時間做不同的事情

一個簡單的用例爲多線程是這樣的:

startBackgroundThread(...); 
doSomethingElseWhileBackgroundThreadIsRunning(...); 
waitForResultFromBackgroundThread(...); 

如果你不打算做別的事情,而後臺線程運行,那麼你會更好,簡化了編程並在一個線程中完成所有工作。


附言:如果你想從一個後臺任務傳達一個結果到前臺線程,你可以嘗試使用java.util.concurrent.SynchronousQueue實例。

相關問題