2012-03-01 139 views
1

我仍然在學習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,但有人建議我使用異步任務。無論哪種方式,讓我知道在哪裏以及如何實現其中之一;我真的很感激它。謝謝!

+0

需要等待外部系統,外線電話需要在基本異步一切。你的情況是send()需要異步。 – Rudy 2012-03-01 10:41:46

回答

3

在這種情況下,基本上你會將發送方法包裝到asynctask的doInBackground()方法中,並且將onPostExecute(...)中的結果設置爲DB。如果你喜歡,使AsyncTask成爲一個內部類。有很多關於如何製作AsyncTask的例子。 這裏有個例子只是一個問題

Using AsyncTask with database

Android AsyncTask and SQLite DB instance

這個網站有很好的教程 http://www.vogella.de/articles/AndroidPerformance/article.html

和ofcourse馬克·墨菲(CommonsWare)的 https://github.com/commonsguy/cw-lunchlist/blob/master/15-Internet/LunchList/src/apt/tutorial/FeedActivity.java


乾杯

+0

我不應該爲'LocationActivity'類完成整個任務嗎? – mkyong 2012-03-01 10:50:01

+0

不是真的,但仍然可以在這裏檢查http://about-android.blogspot.com/2010/04/find-current-location-in-android-gps.html ...和這裏http://stackoverflow.com/問題/ 8253887/how-to-excute-asynctask-inside-onlocationchanged-method-in-android並檢查這一個---我猜你的完美情況://stackoverflow.com/questions/7617957/should-i-create -service-for-gps-tracking-app – 2012-03-01 10:54:22

+0

此外,由於每秒都會調用send方法,每次都會創建一個新任務嗎? – mkyong 2012-03-01 10:56:37

1

我認爲, 「GPS採集器」 是更適合一項服務。

您的服務可能看起來像:

import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Binder; 
import android.os.Bundle; 
import android.os.IBinder; 

public class GPSCollectService extends Service implements LocationListener{ 
private LocationManager mLocationManager; 

public class GPSBinder extends Binder { 
    GPSCollectService getService() { 
     return GPSCollectService.this; 
    } 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return mBinder; 
} 

private final IBinder mBinder = new GPSBinder(); 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_STICKY; 
} 

@Override 
public void onCreate() { 
    startservice(); 
} 

@Override 
public void onDestroy(){ 
    mLocationManager.removeUpdates(this); 
    mLocationManager = null; 
} 

private void startservice() { 
    mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this); 
} 

public void onLocationChanged(Location arg0) { 
    if (arg0 != null){ 
     //Your database storing code here 
     } 
    } 

public void onProviderDisabled(String arg0) {} 
public void onProviderEnabled(String arg0) {} 
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {} 
} 

,並在您的主要活動:

private Intent msvcGPSCollect = null; 

@Override 
public void onDestroy(){ 
    finishServices(); 

    super.onDestroy(); 
} 

private void startBackgroundServices(){ 
    msvcGPSCollect = new Intent(this, GPSCollectService.class); 
    startService(msvcGPSCollect); 
} 

private void finishServices(){ 
    if (msvcGPSCollect != null) 
     stopService(msvcGPSCollect); 
} 

編輯:我沒有真正回答您的問題!

當我把:

\\ Your database storing code here 

你需要調用自己的異步任務。一個異步任務調用的

實例:一個異步任務

PushGPSAsync myAsyncTask = new PushGPSAsync(); 
myAsyncTask.execute(); 

例子:

public class PushGPSAsync extends AsyncTask<Void, Void, Boolean>{ 
    @Override 
    protected Boolean doInBackground(Void... params){ 
     pushGPS(); 
     return null; 
    } 

    @Override 
    public void onPostExecute(Boolean result){ 
     //Call a post execute function here 
    } 
} 

private boolean pushGPS(Void... params){ 
    //store the GPS 
}