閱讀Where to place the Asynctask in the Application 和http://android-developers.blogspot.com/2009/05/painless-threading.html優雅的地方哪裏是把端點Builder和的AsyncTask方法所產生的端點方法
的Android Studio將產生5個有用的方法是POJO類端點類和客戶端庫(獲取,插入,列表,刪除和更新)。
試圖在UI線程上這些方法是不允許的,以保護等待時間,所以調用這些方法對另一個線程的情況發生。許多示例顯示了將AsyncTask作爲解決方案進行擴展。
例如,我產生端點等一個叫醫生級別,並以新的醫生加入到數據庫裏面添加MainActivity這個私有類:
private class insertDoctorTask extends AsyncTask<Doctor, Integer, Long> {
protected Long doInBackground(Doctor... ds) {
long res = 1;
try {
Doctor result = endpoint.insertDoctor(ds[0]).execute();
} catch (IOException e) {
e.printStackTrace();
res = 0;
}
return res;
}
}
我需要在其他相同的代碼活動和我不願意複製和粘貼到所有的地方。什麼是優雅的方式,使這個和它的同伴任務(getDoctorTask,listDoctorTask,removeDoctorTask,updateDoctorTask)提供給活動,這樣的代碼是隻在一個地方?哪裏是初始化端點的適當位置?
我創建了一個叫做與公共任務包類名爲insertDoctorTask2,與上面相同。由於「端點」是MainActivity(?)的靜態屬性,因此我必須添加Doctorendpoint myendpoint;以醫生爲終點進行該方法。如果我需要將其用於其他活動,則在MainActivity中構建端點似乎不正確。我想,我需要有一個命懸一線周圍建立端點,這樣我可以不考慮使用它的活動... – cube108
'Doctorendpoint.Builder建設者=新Doctorendpoint.Builder(AndroidHttp.newCompatibleTransport(), 新JacksonFactory(),NULL) ; builder.setApplicationName(「M25」); builder = CloudEndpointUtils.updateBuilder(builder); 終點= builder.build();'是我的意思,當我提到「建立端點」 – cube108