我仍然在學習Java/Android開發,我需要一些指導來實現異步任務。我主要不確定在我的程序中從哪裏開始。我在下面概述了一些代碼,有人可以告訴我在哪裏以及如何執行任務?我的應用程序每秒都會將GPS座標發送到數據庫,並且我需要一個單獨的任務,所以我不會阻塞主線程並冒ARN錯誤的風險。這是我的代碼:從哪裏開始異步任務 - Android
這第一塊是從我的主要活動。當按鈕被按下時,啓動倒計時三秒鐘,當完成時(onFinish),用戶數據被髮送到一個數據庫(SendUserActivity.sendId...
,這實際上是一個類,而不是一個活動,只是名字很差),然後應用程序開始跟蹤用戶並每秒鐘將座標發送到不同的數據庫(location.startLocation...
)(兩個數據庫以避免重複所有用戶的數據)。
MainActivity.java:
public void onFinish() {
button.setText("SENT");
SendUserActivity.sendId(usr_id1, first, last);
location.startLocation(getBaseContext(), usr_id1);
這是代碼從LocationActivity
類第二塊(也是一類,而不是一個活動,命名差再次)。它每秒都會請求位置更新,然後將其發佈到一個PHP腳本中,該腳本將其插入到MySQL數據庫中。
public class LocationActivity {
private LocationManager locManager;
private LocationListener locListener;
public void startLocation(Context context, String usr_id2)
{
final String usr = usr_id2;
//get a reference to the LocationManager
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location location) {
send(location, usr);
}
public void onProviderDisabled(String provider){
//labelState.setText("Provider OFF");
}
public void onProviderEnabled(String provider){
//labelState.setText("Provider ON ");
}
public void onStatusChanged(String provider, int status, Bundle extras){
//Log.i("", "Provider Status: " + status);
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locListener);
}
public void send(Location loc, String usr_id2) {
Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", lat));
nameValuePairs.add(new BasicNameValuePair("lon", lon));
nameValuePairs.add(new BasicNameValuePair("id", usr_id2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
重申我的問題,我將如何實現一個異步任務發送GPS信息到數據庫?我已閱讀IntentServices,但有人建議我使用異步任務。無論哪種方式,讓我知道在哪裏以及如何實現其中之一;我真的很感激它。謝謝!
需要等待外部系統,外線電話需要在基本異步一切。你的情況是send()需要異步。 – Rudy 2012-03-01 10:41:46