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
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
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" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.