как получить одно местоположение GPS мобильного телефона в моем приложении для Android?

Я хочу знать, как реализовать, чтобы получить местоположение на одном мобильном телефоне и показать местоположение этого мобильного телефона.

Так же, как приложение Uber Cab. Когда мы просим подвезти из одного места в другое место. Они назначают нам одно такси. Тем временем приложение также отображает местонахождение таксиста. Я хочу знать, как они реализуют, если какой-то орган направит нас или даст соответствующий документ для этого. Заранее спасибо, это очень важно


person Bhaumik    schedule 04.03.2016    source источник
comment
используйте эту ссылку, есть несколько хороших решений..   -  person Haniyeh Khaksar    schedule 04.03.2016
comment
Сделайте лучший поиск, stackoverflow.com/questions/1513485/ stackoverflow.com/questions/17591147/   -  person rafaello    schedule 04.03.2016


Ответы (2)


Вы используете следующий код для отслеживания изменений в событиях местоположения.

DeviceLocation.java

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class DeviceLocation extends Service {

    private GPSTracker gpsTracker;
    private Handler handler = new Handler();
    private Timer timer = new Timer();
    private Distance pastDistance = new Distance();
    private Distance currentDistance = new Distance();
    public static double DISTANCE;
    boolean flag = true;
    private double totalDistance;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.v("Location1", "********* " + Thread.currentThread().getId());
        gpsTracker = new GPSTracker(this);
//  below code is to track change in past and present location events
//        TimerTask timerTask = new TimerTask() {
//
//            @Override
//            public void run() {
//                Log.v("Location2", "********* " + Thread.currentThread().getId());
//                handler.post(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        Log.v("Location3", "********* " + Thread.currentThread().getId());
//                        if (flag) {
//                            pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
//                            pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
//                            flag = false;
//                        } else {
//                            currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
//                            currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
//                            flag = comapre_LatitudeLongitude();
//                        }
//                    }
//                });
//            }
//        };
//        timer.schedule(timerTask, 0, 5000);

        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                Log.v("Location2", "********* " + Thread.currentThread().getId());
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                      // send to server or device you need to send via GCM 
SendMessage(String.valueOf(gpsTracker.getLocation().getLatitude())
String.valueOf(gpsTracker.getLocation().getLongitude()));
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 5000);
        return START_STICKY;
    }

    public void Track(String lat, String lng) {
        Sender sender = new Sender("AIzaSyAlXGdj3TGPAnKBiuhn4yxXgLKxwmHJnMY");
        String GcmId = new TrackPref(this).getTrackId();
        Message message = new Message.Builder()
                .collapseKey("and_app")
                .delayWhileIdle(true)
                .addData("action", "location")
                .addData("Lat", lat)
                .addData("Long", lng)
                .timeToLive(600)
                .build();

        Result result = null;
        try {
            result = sender.send(message, GcmId, 2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (result.getMessageId() != null) {
            String canonicalRegId = result.getCanonicalRegistrationId();
            Log.d("abc", result.toString());
        } else {
            String error = result.getErrorCodeName();
        }
    }

    private void SendMessage(final String lat, final String lng) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                Track(lat, lng);
                return null;
            }

            @Override
            protected void onPostExecute(String msg) {

            }
        }.execute();
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("--------------------------------onDestroy -stop service ");
        timer.cancel();
        DISTANCE = totalDistance ;
    }

    private double distance(double lat1, double lon1, double lat2, double lon2) {
        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        return (dist);
    }

    private double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }

    private double rad2deg(double rad) {
        return (rad * 180.0 / Math.PI);
    }

    public boolean comapre_LatitudeLongitude() {
        Log.v("Location4", "********* " + Thread.currentThread().getId());
        if (pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()) {
            return false;
        } else {

            final double distance = distance(pastDistance.getLatitude(), pastDistance.getLongitude(), currentDistance.getLatitude(), currentDistance.getLongitude());
            System.out.println("Distance in mile :" + distance);
            handler.post(new Runnable() {

                @Override
                public void run() {
                    float kilometer = 1.609344f;
                    Log.v("Location5", "********* " + Thread.currentThread().getId());
                    totalDistance = totalDistance + distance * kilometer;
                    DISTANCE = totalDistance;

                }
            });
            return true;
        }
    }
}

Для получения подробной информации следуйте коду из приведенной ниже библиотеки. https://github.com/raviteja06/TrackMyClient

это было сделано некоторое время назад, обязательно обновите библиотеки до последней версии.

person Ravi Gadipudi    schedule 04.03.2016

Попробуйте со следующим кодом:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

    GoogleApiClient googleApiClient;
    int REQUEST_CHECK_SETTINGS = 1;
    Location mLastLocation;
    LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        checkForGPS();
    }

    public void checkForGPS(){
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();
            googleApiClient.connect();

            if(!((LocationManager)getSystemService(Context.LOCATION_SERVICE)).isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                //prompt user to enable gps
                locationRequest = LocationRequest.create();
                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                locationRequest.setInterval(5000);
                locationRequest.setFastestInterval(3000);
                LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);
                builder.setAlwaysShow(true);

                PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());

                result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                    @Override
                    public void onResult(LocationSettingsResult result) {
                        final Status status = result.getStatus();
                        final LocationSettingsStates states = result.getLocationSettingsStates();
                        switch (status.getStatusCode()) {
                            case LocationSettingsStatusCodes.SUCCESS:
                                // All location settings are satisfied. The client can initialize location
                                // requests here.
                                break;
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                // Location settings are not satisfied. But could be fixed by showing the user
                                // a dialog.
                                try {
                                    // Show the dialog by calling startResolutionForResult(),
                                    // and check the result in onActivityResult().
                                    status.startResolutionForResult(
                                            MainActivity.this,
                                            REQUEST_CHECK_SETTINGS);
                                } catch (IntentSender.SendIntentException e)     {
                                    // Ignore the error.
                                }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                // Location settings are not satisfied. However, we have no way to fix the
                                // settings so we won't show the dialog.
                                break;
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        // put your code here to play with Location object
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
}

Вот некоторые полезные импорты, которые могут вам понадобиться:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;

Не забудьте объявить эти разрешения в манифесте:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
person zeeali    schedule 04.03.2016