2017-05-30 112 views
0

我想將我的位置座標發送到Web服務,我有一個名爲「LocationService」的類應該這樣做,但在執行應用程序時什麼也沒有發生......將GPS位置發送到Web服務

LocationService

public class LocationService extends Service implements LocationListener{ 

public String LOG = "Log"; 
UserSessionManager session; 

private Context mContext = null; 

boolean isGPSEnabled = false; 
boolean isNetworkEnabled = false; 
boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second 

// Declaring a Location Manager 
protected LocationManager locationManager; 

public LocationService(Context context) { 
    this.mContext = context; 
} 

public LocationService() { 
    super(); 
    mContext = LocationService.this; 
} 

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

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 
    Log.i(LOG, "Service started"); 
    Log.i("asd", "This is sparta"); 

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

    new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId); 

    return START_STICKY; 
} 


@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.i(LOG, "Service created"); 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    Log.i(LOG, "Service destroyed"); 
} 

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


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

     try { 

      HttpURLConnection urlConnection = null; 
      String posicionActual = ""; 
      BufferedReader reader = null; 
      OutputStream os = null; 
      InputStream inputStream = null; 

      Log.i("string", la[0]); 
      String longi = la[0];  // Recibo la longitud. 
      String lati = la[1];  // Recibo la latitud. 
      String idUsuario = la[2]; // Recibo Id del usuario. 

      JSONObject coordenadas = new JSONObject(); 
      coordenadas.put("Latitud",lati); 
      coordenadas.put("Longitud",longi); 

      posicionActual = coordenadas.toString(); 

      URL url = new URL("http://localhost:8081/odata/Usuarios("+idUsuario+")/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(posicionActual.getBytes()); 


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

     return "call"; 
    } 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      if (isNetworkEnabled) { 
       //updates will be send according to these arguments 
       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

       } 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return location; 
} 




@Override 
public void onLocationChanged(Location location) { 
    //Llamo al servidor cada segundo y le envío mi posición 
    HashMap<String, String> user = session.obtenerRolyId(); 
    String usuarioId = user.get(UserSessionManager.KEY_ID); 
    new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()), usuarioId); 


} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

}} 

我打電話給我的服務從活動:

protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_user_map); 

    startService(new Intent(UserMapActivity.this, LocationService.class));} 
+0

添加logcat的輸出以瞭解問題的原因 – Ale

回答

1

開始,移動對onStartCommand的權限檢查,你只需要檢查一次。並請,要求用戶授予您的許可,它是這樣的簡單:這個

new SendToServer().execute(Double.toString(location.getLongitude()), Double.toString(location.getLatitude()),usuarioId); 

您已經

new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId); 

ActivityCompat.requestPermissions(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION, SINGLE_PERMISSION_REQUEST_CODE); 

public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) { 
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
     Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show(); 
     d(TAG,"Permission " + permissions[0] +" granted"); 
    } 
} 

然後,在onLocationChange替換此具有來自提供者的最後位置,您不必從getLastKnownLocation中重新獲取它

在服務器連接中,您應該添加以檢查一切正常:

os.flush(); 
os.close(); 
int serverResponse = urlConnection.getResponseCode(); 
String serverMsg = urlConnection.getResponseMessage(); 
urlConnection.disconnect(); 
Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);