我还在学习Java / Android开发,我需要一些指导才能实现异步任务。我大多不确定在我的程序中从哪里开始它。我在下面概述了一些代码,有人可以告诉我在哪里以及如何实现任务?我的应用程序每秒向数据库发送GPS坐标,我需要一个单独的任务,所以我不会陷入主线程并冒着ARN错误的风险。这是我的代码:
这第一个块来自我的主要活动。当按下按钮时,启动三秒倒计时,当它完成时(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
类的第二个代码块(也是一个类,而不是一个活动,再次命名不好)。它每秒请求一次位置更新,然后将其发布到将脚本插入MySQL数据库的PHP脚本中。
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 :(得分:3)
在这种情况下,基本上你将send方法包装到asynctask的doInBackground()
方法中,onPostExecute(...)
中的结果将被设置到DB中。如果你愿意,让AsyncTask成为一个内部类。有很多关于如何制作AsyncTask的例子。
这里仅举一个问题
Using AsyncTask with database和
Android AsyncTask and SQLite DB instance。
这个网站有很好的教程 http://www.vogella.de/articles/AndroidPerformance/article.html
Mark Murphy(CommonsWare) https://github.com/commonsguy/cw-lunchlist/blob/master/15-Internet/LunchList/src/apt/tutorial/FeedActivity.java干杯
答案 1 :(得分: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
}