Android : Thread OnFinish() --> 调用另一个函数



我有一个android应用程序,我在其中通过json上传一些数据。我在一个单独的线程中执行这个过程。

问题:有没有办法知道这个线程何时成功结束。这样我就可以为所有发送的数据干杯了

代码

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

最新更新