在服务中调用asynctask是否正确?

时间:2017-06-02 21:11:02

标签: java android android-asynctask

我尝试在" onLocationChanged"中调用asynctask。方法,但asynctask永远不会收到参数。我的服务获取我的位置的每个更改的坐标,并在控制台中很好地显示它们。

在我的服务中

public void onLocationChanged(Location location){

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        Log.e(TAG, "onLocationChanged: " + location);
        mLastLocation.set(location);

        JSONObject actualPosition = new JSONObject();

        try {

            actualPosition.put("Latitude", latitude);
            actualPosition.put("Longitude", longitude);

            new AsyncTaskServerPosition.SendToServer().execute(actualPosition.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

修改

我的asynctask

public class AsyncTaskServerPosition{

private static final String TAG = "ASYNCTASK";
private static UserSessionManager session;


public static class SendToServer extends AsyncTask<String, String, String>
{

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... location) {

        try {

            HashMap<String, String> user = session.obtenerRolyId();
            String userId = user.get(UserSessionManager.KEY_ID);

            Log.d(TAG, "Location: " +location);
            HttpURLConnection urlConnection = null;
            String actualPosition = location[0];
            BufferedReader reader = null;
            OutputStream os = null;
            InputStream inputStream = null;

            URL url = new URL("http://localhost:8081/odata/Usuarios("+userId+")/ActualizarPosicion");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");

            urlConnection.connect();

            os = new BufferedOutputStream(urlConnection.getOutputStream());
            os.write(actualPosition.getBytes());

            os.flush();
            os.close();

            int serverResponse = urlConnection.getResponseCode();
            String serverMsg = urlConnection.getResponseMessage();
            urlConnection.disconnect();

            Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);


        } catch (Exception e) {
            Log.i("error", e.toString());
        }

        return "call";
    }

    @Override
    protected void onPostExecute(String result) {
    }

}}

服务完成

public class ServicePosition extends Service{

private static final String TAG = "TESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;

UserSessionManager session;

private class LocationListener implements android.location.LocationListener{

    Location mLastLocation;
    public LocationListener(String provider)
    {
        Log.e(TAG, "LocationListener " + provider);
        mLastLocation = new Location(provider);
    }
    @Override
    public void onLocationChanged(Location location)
    {

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        Log.e(TAG, "onLocationChanged: " + location);
        mLastLocation.set(location);

        JSONObject actualPosition = new JSONObject();

        try {

            actualPosition.put("Latitud", latitude);
            actualPosition.put("Longitud", longitude);

            new AsyncTaskServerPosition.SendToServer().execute(actualPosition.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void onProviderDisabled(String provider)
    {
        Log.e(TAG, "onProviderDisabled: " + provider);
    }
    @Override
    public void onProviderEnabled(String provider)
    {
        Log.e(TAG, "onProviderEnabled: " + provider);
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
        Log.e(TAG, "onStatusChanged: " + provider);
    }
}
LocationListener[] mLocationListeners = new LocationListener[] {
        new LocationListener(LocationManager.GPS_PROVIDER),
        new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Override
public IBinder onBind(Intent arg0)
{
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.e(TAG, "onStartCommand");
    super.onStartCommand(intent, flags, startId);

    return START_NOT_STICKY;
}
@Override
public void onCreate()
{
    Log.e(TAG, "onCreate");
    initializeLocationManager();
    try {
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[1]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "No puede solicitar la actualización de la ubicacion", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "El proveedor de gps no existe, " + ex.getMessage());
    }
    try {
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[0]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "No puede solicitar la actualización de la ubicacion", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "El proveedor de gps no existe " + ex.getMessage());
    }
}
@Override
public void onDestroy()
{
    Log.e(TAG, "onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG, "fail to remove location listners, ignore", ex);
            }
        }
    }
}
private void initializeLocationManager() {
    Log.e(TAG, "initializeLocationManager");
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}}

0 个答案:

没有答案