如何在 android 中每秒更新一次 gps 坐标?

How to update gps coordinate every second in android?

我是 android 开发的新手,这是我的第一个应用程序。我的应用程序是使用另一个应用程序跟踪一个 phone。我现在已经设法完成第一个发送 gps 坐标的应用程序。现在我正在做第二个应用程序,到目前为止,应用程序可以从 mysql 服务器检索 GPS 坐标并将其显示在 google 地图上。问题是我的 mysql 数据库每秒更新一次,我无法在我的应用程序中刷新我的 gps 坐标。我尝试使用

 new Handler().postDelayed(new Runnable() {
        public void run() {
            // call JSON methods here
            new JsonReadTask ().execute();
        }
    }, 60000  );

调用我的异步任务,但应用程序刚刚崩溃并显示一条错误消息

E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process

我一直在搜索,由于我对 android 缺乏了解,我发现很难更改和实施解决方案来解决我的问题。谁能帮帮我吗。

我的activity代码

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MyActivity extends FragmentActivity {



private String jsonResult;
private String url = "http://address.com/recieve1.php";




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myactivity);
    accessWebService();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        try {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {
            // e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return answer;
    }

    @Override
    protected void onPostExecute(String result) {
        jsonvalue();
    }
}// end async task

public void accessWebService() {
    JsonReadTask task = new JsonReadTask();
    // passes values for the urls string array
    task.execute(new String[] { url });
}



public void jsonvalue() {
    List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();


    try {
        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("my_coor");
        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String latitude = jsonChildNode.optString("latitude");
            String longitude = jsonChildNode.optString("longitude");
            String coordinates[] = {latitude, longitude};
            double lat = Double.parseDouble(coordinates[0]);
            double lng = Double.parseDouble(coordinates[1]);

            // Getting reference to SupportMapFragment
            SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);

            // Creating GoogleMap from SupportMapFragment
            mapView = fragment.getMap();

            LatLng location;
            location = new LatLng(lat, lng);

            mapView.addMarker(new MarkerOptions().position(location));
            mapView.moveCamera(CameraUpdateFactory.newLatLng(location));
            mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                Toast.LENGTH_SHORT).show();

    }






    }

完整的错误日志

04-22 20:50:25.236  11023-11023/com.unmcbus.unmcbustracker E/Zygote﹕     MountEmulatedStorage()
04-22 20:50:25.236  11023-11023/com.unmcbus.unmcbustracker E/Zygote﹕ v2
04-22 20:50:25.236  11023-11023/com.unmcbus.unmcbustracker E/SELinux﹕ [DEBUG]   get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
04-22 20:51:34.331  11023-12546/com.unmcbus.unmcbustracker E/AndroidRuntime﹕   FATAL EXCEPTION: AsyncTask #2
Process: com.unmcbus.unmcbustracker, PID: 11023
java.lang.RuntimeException: An error occured while executing   doInBackground()
        at android.os.AsyncTask.done(AsyncTask.java:300)
        at   java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
        at   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
 Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
        at   com.unmcbus.unmcbustracker.UNMCtoTTSActivity$JsonReadTask.doInBackground(UNMCtoT     TSActivity.java:66)
        at com.unmcbus.unmcbustracker.UNMCtoTTSActivity$JsonReadTask.doInBackground(UNMCtoTTSActivity.java:61)
        at android.os.AsyncTask.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

请post您完整的错误日志,以便清楚地了解错误。

不过我发现你的代码有问题 --> 您不能从后台线程执行任何 UI 操作(doInBackground() 方法)

我相信您执行任务的方式,doInBackground 中的数组将为空,因为您没有传递 URL。

据我所知,这应该通过 URL:

 new Handler().postDelayed(new Runnable() {
    public void run() {
        // call JSON methods here
        accessWebService();
    }
}, 60000  );