简体   繁体   English

如何在我的Android应用程序中获取一个手机GPS位置?

[英]how to get one mobile phone gps location in my android App?

I want to know how to implement to get location on one mobile phone and show that mobile phone location. 我想知道如何实现在一部手机上的位置并显示该手机的位置。

Just like uber cab application. 就像超级出租车应用程序一样。 When we ask for the ride from one place to another place. 当我们要求从一个地方到另一个地方的旅程。 They assign one cab for us Meanwhile there app also display the location of the cab driver. 他们为我们分配了一辆出租车。同时,该应用还显示了出租车司机的位置。 I want to know how they implement if some body guide us or give related document for this. 我想知道如果某个机构指导我们或为此提供相关文件,他们将如何实施。 Thanks in Advance, Its very Appriciable 在此先感谢,它非常适用

You this following code to track changes in location events 您可以使用以下代码跟踪位置事件的变化

DeviceLocation.java 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;
        }
    }
}

For detailed information follow the code from below library. 有关详细信息,请遵循以下库中的代码。 https://github.com/raviteja06/TrackMyClient https://github.com/raviteja06/TrackMyClient

this was done while back, make sure to update libraries to latest. 这是在返回时完成的,请确保将库更新为最新。

Try with following code: 尝试以下代码:

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);
    }
}

Here are some useful imports you may require: 以下是您可能需要的一些有用的导入:

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;

Don't forget to declare these permissions in Manifest: 不要忘记在清单中声明以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM