2015-12-22 127 views
0

我有一個android應用程序,我可以通過json上傳一些數據。我在一個單獨的線程中執行這個過程。Android:線程OnFinish() - >調用另一個函數

問:是否有辦法知道此線程何時成功結束。這樣我就可以打電話給吐司說所有發送的數據。

代碼

protected void sendJson(){ 
    if(isOnline()){ 
     Thread t = new Thread() { 
      public void run() { 
       Looper.prepare(); //For Preparing Message Pool for the child Thread 
       HttpClient client = new DefaultHttpClient(); 
       HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000); //Timeout Limit 
       HttpResponse response; 
       // JSONObject json = new JSONObject(); 

       try { 
        String URL ="http://myservice.azurewebsites.net/Service/RegisterStudent"; 
        HttpPost post = new HttpPost(URL); 

        JSONObject StudentData = new JSONObject(); 

        String android_id = Secure.getString(AdminSection.this.getContentResolver(),Secure.ANDROID_ID); 
        DBHelper db = new DBHelper(getApplicationContext()); 

        List<StudentClass> StudentDataAll = db.getAllStudentData(); 
        for(int iCount=0; iCount< StudentDataAll.size(); iCount++){ 
         StudentClass objStudentClass= (StudentClass)StudentDataAll.get(iCount); 
         String sSingleStudentCompleteDetails= android_id +","+ objStudentClass.RegistrationId + "," + objStudentClass.Name + "," + objStudentClass.SchoolID + "," + objStudentClass.Class + "," + objStudentClass.RollNo + "," + objStudentClass.RegistrationDate; 
         String sSingleStudentCompleteResponse = "";  
         String strStudentID = objStudentClass.RegistrationId;   
         StudentIDForSave = strStudentID; 

         List<StudentResponse> StudentResponse = db.getStudentResponseOnStudentID(strStudentID); 

         for(int iOptionCount=0; iOptionCount<StudentResponse.size(); iOptionCount++){ 

          StudentResponse objStudentResponse=StudentResponse.get(iOptionCount); 
          if(iOptionCount>0) 
           sSingleStudentCompleteResponse += ","; 

          sSingleStudentCompleteResponse += objStudentResponse.QuestionID + "-" + objStudentResponse.OptionID; 

         } 

         StudentData.put("StudentDetails", sSingleStudentCompleteDetails); 
         StudentData.put("Responses", sSingleStudentCompleteResponse); 

         JSONObject finaldata = new JSONObject(); 
         finaldata.put("RegisterStudentRequest", StudentData); 

         // Toast.makeText(getBaseContext(), finaldata.toString(), Toast.LENGTH_LONG).show(); 



         StringEntity se = new StringEntity(finaldata.toString()); 
         se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
         post.setEntity(se); 
         response = client.execute(post); 

         String jsonString = EntityUtils.toString(response.getEntity()); 


         JSONObject resp = null; 
         resp = new JSONObject(jsonString); 
         JSONObject UploadStudentDataResult = resp.getJSONObject("RegisterStudentResult"); 

         String strMessage = UploadStudentDataResult.getString("IsUploaded"); 
         // Toast.makeText(getBaseContext(), strMessage, Toast.LENGTH_LONG).show(); 

         if (StudentIDForSave != null){ 
          SQLiteDatabase db1; 
          ContentValues values = new ContentValues(); 
          values.put(DBHelper.isUploaded, strMessage); 


          // Call update method of SQLiteDatabase Class and close after 
          // performing task 
          db1 = helper.getWritableDatabase(); 
          db1.update(DBHelper.TABLEStudent, values, DBHelper.S_ID + "=?", 
          new String[] { StudentIDForSave}); 
          db1.close(); 
         } 
        } 
        // tvSetCount.setText("Data Uploaded Successfully"); 
       }catch(Exception e) { 
        e.printStackTrace(); 
        //createDialog("Error", "Cannot Estabilish Connection"); 
       } 
       Looper.loop(); //Loop in the message queue 
      } 
     }; 
     t.start(); 
    } 
} 
+0

'Thread.join'? –

+0

你可否詳細說明。我是新來的android –

+0

哈哈! Googlin .... –

回答

0
You can use Thread and handler as below example shows. 
public class ThreadHandlerAndroidExample extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.android_example_thread_handler); 

     final Button GetServerData = (Button) findViewById(R.id.GetServerData); 


     // On button click call this listener 
     GetServerData.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 

       Toast.makeText(getBaseContext(), 
         "Please wait, connecting to server.", 
         Toast.LENGTH_SHORT).show(); 


       // Create Inner Thread Class 
       Thread background = new Thread(new Runnable() { 

        private final HttpClient Client = new DefaultHttpClient(); 
        private String URL = "http://androidexample.com/media/webservice/getPage.php"; 

        // After call for background.start this run method call 
        public void run() { 
         try { 

          String SetServerString = ""; 
          HttpGet httpget = new HttpGet(URL); 
          ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
          SetServerString = Client.execute(httpget, responseHandler); 
          threadMsg(SetServerString); 

         } catch (Throwable t) { 
          // just end the background thread 
          Log.i("Animation", "Thread exception " + t); 
         } 
        } 

        private void threadMsg(String msg) { 

         if (!msg.equals(null) && !msg.equals("")) { 
          Message msgObj = handler.obtainMessage(); 
          Bundle b = new Bundle(); 
          b.putString("message", msg); 
          msgObj.setData(b); 
          handler.sendMessage(msgObj); 
         } 
        } 

        // Define the Handler that receives messages from the thread and update the progress 
        private final Handler handler = new Handler() { 

         public void handleMessage(Message msg) { 

          String aResponse = msg.getData().getString("message"); 

          if ((null != aResponse)) { 

           // ALERT MESSAGE 
           Toast.makeText(
             getBaseContext(), 
             "Server Response: "+aResponse, 
             Toast.LENGTH_SHORT).show(); 
          } 
          else 
          { 

            // ALERT MESSAGE 
            Toast.makeText(
              getBaseContext(), 
              "Not Got Response From Server.", 
              Toast.LENGTH_SHORT).show(); 
          }  

         } 
        }; 

       }); 
       // Start Thread 
       background.start(); //After call start method thread called run Method 
      } 
     }); 

    } 

} 
+0

很好的答案..但我不想改變現有的代碼 –

+0

謝謝。你不需要更改代碼太多,只需要在你的類中添加msg方法和處理程序。 –