I'm working with Weather Underground API where I can get weather of a place in 2 ways:
Writing directly the name of the city and nation (example:http://api.wunderground.com/api/*MyKey*/conditions/q/It/Venice.json)
Get the weather of every place have latitude/longitude (example:http://api.wunderground.com/api/*MyKey*/conditions/q/45.43972222,12.33194444.json)
I'm interested in the second way so I'm trying to get my position (that works in an Activity).
FirstActivity.java: (the position is displayed with no problem)
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
TextView textview1 = (TextView)findViewById(R.id.fieldLatitude);
textview1.setText(stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
TextView textview2 = (TextView)findViewById(R.id.fieldLongitude);
textview2.setText(stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
AsyncTask:
public class Conditions extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_conditions);
new WeatherConditions(this).execute();
}
private class WeatherConditions extends AsyncTask<String, String, String> {
private Context mContext;
public WeatherConditions (Context context){
mContext = context;
}
#Override
protected String doInBackground(String... uri) {
GPSTracker gpsTracker = new GPSTracker(mContext);
String latitudine = null;
String longitudine = null;
if (gpsTracker.canGetLocation())
{
latitudine = String.valueOf(gpsTracker.latitude);
longitudine = String.valueOf(gpsTracker.longitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
String responseString = null;
try {
HttpClient client = new DefaultHttpClient();
URI apiCall = new URI("api.wunderground.com/api/51cda8abeca78e10/conditions/q/"
+ latitudine
+","
+ longitudine
+".json");
HttpGet request = new HttpGet();
request.setURI(apiCall);
HttpResponse response = client.execute(request);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("TAG", "some sort of problem encountered", e);
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
...
}
}
}
Where I get this message in the LogCat: Can't create handler inside thread that has not called Looper.prepare()
Here's GPSTracker.java:
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
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);
updateGPSCoordinates();
}
}
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);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation()
{
return this.canGetLocation;
}
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Attenzione!");
alertDialog.setMessage("Abilita il GPS");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("CLOSE", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
return geocoder.getFromLocation(latitude, longitude, 1);
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getAddressLine(0);
}
else
{
return null;
}
}
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getLocality();
}
else
{
return null;
}
}
public String getSubLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getSubLocality();
}
else
{
return null;
}
}
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getPostalCode();
}
else
{
return null;
}
}
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getCountryName();
}
else
{
return null;
}
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
In GPSTracker.java, since getLocation() has context of async task attached to it and looper is not attached to it.
A quick workaround to solve this problem is add Looper.getMainLooper() with requestLocationUpdates, this will attach main looper thread callback with request.
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this, Looper.getMainLooper()
);
Related
Here is my code. I am getting null in googleapiclient.
public class MapsActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener, AdapterView.OnItemClickListener, DriverListner {
View view;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static String TAG = "MAP LOCATION";
Context mContext;
TextView mLocationMarkerText;
private LatLng mCenterLatLong;
private AddressResultReceiver mResultReceiver;
protected String mAddressOutput;
protected String mAreaOutput;
protected String mCityOutput;
protected String mStateOutput;
EditText mLocationAddress;
TextView mLocationText;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
AutoCompleteTextView edtDropLocation;
LatLng source;
LatLng destination;
LinearLayout lytBottomView;
private List < DriverDetail > driverDetailsList = new ArrayList < > ();
DriverListAdapter driverListAdapter;
RecyclerView rv_driver_truck;
DriverDetail driverDetail;
Button book;
int driverId = 0, userId = 0;
String currentLocation = "", dropLocation = "", currentLat = "", currentLong = "", dropLat = "", dropLong = "", token = "",
vehicleId = "", bookingDateTime = "", truckRent = "";
private LocationRequest mLocationRequest;
Date currentTime;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
userId = Integer.parseInt(TruckApplication.ReadStringPreferences(SharedPrefData.PREF_UserId));
token = TruckApplication.ReadStringPreferences(SharedPrefData.PREF_TOKEN);
currentTime = Calendar.getInstance().getTime();
Log.e("##dateandtime", String.valueOf(currentTime));
mLocationMarkerText = view.findViewById(R.id.locationMarkertext);
rv_driver_truck = view.findViewById(R.id.rv_driver_truck);
mLocationAddress = view.findViewById(R.id.Address);
mLocationText = view.findViewById(R.id.Locality);
edtDropLocation = view.findViewById(R.id.edtDropLocation);
lytBottomView = view.findViewById(R.id.lytBottomView);
book = view.findViewById(R.id.book);
edtDropLocation.setAdapter(new MapFragment.GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item_text));
edtDropLocation.setOnItemClickListener(this);
mLocationText.setOnClickListener(view - > openAutocompleteActivity());
mapFragment.getMapAsync(this);
if (checkPlayServices()) {
if (!AppUtils.isLocationEnabled(getContext())) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setMessage("Location not enabled!");
dialog.setPositiveButton("Open location settings", (paramDialogInterface, paramInt) - > {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
});
dialog.setNegativeButton("Cancel", (paramDialogInterface, paramInt) - > {});
dialog.show();
}
buildGoogleApiClient();
} else {
Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
rv_driver_truck.setLayoutManager(linearLayoutManager);
rv_driver_truck.setItemAnimator(new DefaultItemAnimator());
getDriverList();
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBookRequest();
}
});
mResultReceiver = new AddressResultReceiver(new Handler());
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraChangeListener(cameraPosition - > {
Log.d("##Camera postion change" + "", cameraPosition + "");
mCenterLatLong = cameraPosition.target;
mMap.clear();
try {
Location mLocation = new Location("");
mLocation.setLatitude(mCenterLatLong.latitude);
mLocation.setLongitude(mCenterLatLong.longitude);
currentLat = String.valueOf(mCenterLatLong.latitude);
currentLong = String.valueOf(mCenterLatLong.longitude);
startIntentService(mLocation);
mLocationMarkerText.setText(getCompleteAddressString(mLocation.getLatitude(), mLocation.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
});
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
changeMap(mLastLocation);
Log.d(TAG, "ON connected");
} else
try {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
try {
if (location != null)
changeMap(location);
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
#Override
public void onStart() {
super.onStart();
try {
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
} catch (RuntimeException e) {
e.printStackTrace();
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {}
return false;
}
return true;
}
private void changeMap(Location location) {
Log.d(TAG, "Reaching map" + mMap);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mMap != null) {
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng latLong;
latLong = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(10 f).tilt(50).build();
mMap.setMyLocationEnabled(true);
/* mMap.getUiSettings().setMyLocationButtonEnabled(true);*/
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
getCompleteAddressString(location.getLatitude(), location.getLongitude());
mLocationMarkerText.setText(getCompleteAddressString(location.getLatitude(), location.getLongitude()));
startIntentService(location);
} else {
Toast.makeText(getContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
String str = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
LatLng lastLocation = source;
edtDropLocation.setText(str);
dropLocation = str;
Geocoder coder = new Geocoder(getContext());
try {
ArrayList < Address > adresses = (ArrayList < Address > ) coder.getFromLocationName(str, 50);
for (Address add: adresses) {
double longitude = add.getLongitude();
double latitude = add.getLatitude();
dropLat = String.valueOf(latitude);
dropLong = String.valueOf(longitude);
destination = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(destination);
mMap.clear();
markerOptions.title(str);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.droppoint));
mMap.animateCamera(CameraUpdateFactory.newLatLng(destination));
mMap.addMarker(markerOptions);
getDriverList();
lytBottomView.setVisibility(View.VISIBLE);
driverListAdapter = new DriverListAdapter(getActivity(), driverDetailsList, this);
rv_driver_truck.setAdapter(driverListAdapter);
/* new GetPathFromLocation(lastLocation, destination, new DirectionPointListener() {
#Override
public void onPath(PolylineOptions polyLine) {
mMap.addPolyline(polyLine);
lytBottomView.setVisibility(View.VISIBLE);
}
}).execute();*/
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public DriverDetail driverDetail(DriverDetail driverDetail1) {
driverDetail = driverDetail1;
driverId = driverDetail1.getId();
truckRent = driverDetail1.getVehicleRent();
// Log.e("##DriverId", truckRent);
return driverDetail;
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);
mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);
mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);
displayAddressOutput();
if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
}
}
}
protected void displayAddressOutput() {
try {
if (mAreaOutput != null)
mLocationAddress.setText(mAddressOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void startIntentService(Location mLocation) {
Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);
intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);
getActivity().startService(intent);
}
private void openAutocompleteActivity() {
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(getActivity());
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException e) {
GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(),
0 /* requestCode */ ).show();
} catch (GooglePlayServicesNotAvailableException e) {
String message = "Google Play Services is not available: " +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(mContext, data);
LatLng latLong;
latLong = place.getLatLng();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19 f).tilt(70).build();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(mContext, data);
} else if (resultCode == RESULT_CANCELED) {
}
}
#SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
try {
List < Address > addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
currentLocation = strAdd;
Log.e("My Current loction address", strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
private void getDriverList() {
ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
Call < OnlineDriverList > call = apiInterface.getDriverList();
call.enqueue(new Callback < OnlineDriverList > () {
#Override
public void onResponse(#NonNull Call < OnlineDriverList > call, Response < OnlineDriverList > response) {
// refreshLayout.setRefreshing(false);
if (response.isSuccessful()) {
OnlineDriverList onlineDriverList = response.body();
if (onlineDriverList.getDriverDetails().size() == 0) {
Toast.makeText(getContext(), "No Driver is Available at current Time ", Toast.LENGTH_SHORT).show();
} else {
driverDetailsList = onlineDriverList.getDriverDetails();
TruckBo.getInstance().setDriverArrayList(driverDetailsList);
// driverListAdapter.setData(driverDetailsList);
// refreshLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onFailure(Call < OnlineDriverList > call, Throwable t) {
//refreshLayout.setRefreshing(false);
Log.d("Error", t.getLocalizedMessage());
}
});
}
public void sendBookRequest() {
ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
Call < UserRegistration > call = apiInterface.booking(driverId, userId, truckRent, currentLocation, dropLocation,
currentLat, currentLong, dropLat, dropLong, token, "", ""
);
call.enqueue(new Callback < UserRegistration > () {
#Override
public void onResponse(Call < UserRegistration > call, Response < UserRegistration > response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), "Wait For Respond From Driver Side", Toast.LENGTH_SHORT).show();
lytBottomView.setVisibility(View.GONE);
} else {}
}
#Override
public void onFailure(Call < UserRegistration > call, Throwable t) {
Log.e("Error", t.getLocalizedMessage());
}
});
}
}
I am getting null here:
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
The first time it is not going to the current location and I am getting null googleapiclient, and on move marker, I am fetching address in starting I am not getting current location.
I try to get current location when the app running in background, so I use service. However, the data does not change in background, the service does not work. I want to know the problem. Here is the code of the app.
MainActivity as follow:
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latitude"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Service as follow:
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver =
"com.findmyelderly.findmyelderly.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
} else {
if (isNetworkEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (isGPSEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
build.gradle as follow
.........
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:multidex:1.0.0'
AndroidManifest as follow
..........
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
.........
<service android:name=".GoogleService" android:exported="false" android:enabled="true"/>
</application>
</manifest>
I am very puzzled.
One thing you could try is to check the permissions of the app on the phone itself. I've found with my device (Android version 6.0.1) it's not enough to just add "uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> and
"uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />"
in the manifest, you have to grant permissions to the app manually on the device.
To do this, go to Settings > Apps > 'yourApp' > Permissions and slide across the bar to turn on Location for that app.
I'm new enough to Android apps myself so there may be a bigger problem in your case I'm not sure but worth a try anyway!
The code works in my phone properly but doesn't works sometime. Also, this code doesn't work in other phone properly. I have tried many times. And while sending this app's apk file through xender the installation fails. Please help to improve my code so that it works properly in all phone when location is turned ON.
Mainactivity.java
public class MainActivity extends AppCompatActivity {
TextView result;
Double latitude, longitude;
Geocoder geocoder;
List<Address> addressList;
Getgps gps;
Context mContext;
protected LocationManager locationManager;
boolean isGPSEnabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.abcd);
geocoder = new Geocoder(this, Locale.getDefault());
mContext = this;
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled)
{
getlonglat(); //check location
if(CheckInternetConnection(MainActivity.this)) {
getaddress();
// getlocation
if(result.getText().toString().matches(""))
{
Toast.makeText(mContext, "Poor Internet Connection", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet Connection",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Turn ON Your Location",Toast.LENGTH_LONG).show();
showgpsSettingsAlert();
startActivity(new Intent(MainActivity.this, Main2Activity.class));
Toast.makeText(mContext, " after delay khatey", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void getlonglat() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
Toast.makeText(mContext, "GPS Permission Granted", Toast.LENGTH_SHORT).show();
gps = new Getgps(mContext, MainActivity.this);
// Check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
}
}
public void getaddress() {
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
String address = addressList.get(0).getAddressLine(0);
String area = addressList.get(0).getLocality();
String city = addressList.get(0).getAdminArea();
String country = addressList.get(0).getCountryName();
String postalcode = addressList.get(0).getPostalCode();
String fullAddress = address + ", " + area + ", " + city + ", " + country + ", " + postalcode;
Toast.makeText(mContext, "Internet Permission Granted", Toast.LENGTH_SHORT).show();
result.setText(fullAddress);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static boolean CheckInternetConnection(Context context) {
ConnectivityManager connectivity =
(ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showgpsSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
this.setFinishOnTouchOutside(false);
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
}
}
Getgps.java
package com.example.bibash28.locationfinal2;
/**
* Created by Bibash28 on 11/3/2017.
*/
public class Getgps extends Service
{
private Context mContext; // Flag for GPS status
boolean isGPSEnabled = false; // Flag for network status
boolean canGetLocation = false;
Location location; // Location
Double latitude,longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000;// The minimum distance to change Updates in meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;// 10 meters// The minimum time between updates in milliseconds// 1 minute
Activity activity;
protected LocationManager locationManager;
public Getgps(Context context, Activity activity)
{
this.mContext = context;
this.activity = activity;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
this.canGetLocation = true;
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
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;
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Function to get latitude
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
// Function to get longitude
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
//Function to check GPS/Wi-Fi enabled #return boolean
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I am trying to send coordinates of my position to the web service, I have a class called "LocationService" that should do this, but at the moment of executing the application nothing happens ...
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) {
}}
I call my service from the activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_map);
startService(new Intent(UserMapActivity.this, LocationService.class));}
To start, move the permission check to the onStartCommand, you only have to check it once. And please, ask the user to grant you the permission, it is this simple:
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");
}
}
Then, in the onLocationChange replace this:
new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()),usuarioId);
with this
new SendToServer().execute(Double.toString(location.getLongitude()), Double.toString(location.getLatitude()),usuarioId);
You already have the last location from the provider, you don't have to get it again from the getLastKnownLocation
In the server connection you should add this to check everything worked out well:
os.flush();
os.close();
int serverResponse = urlConnection.getResponseCode();
String serverMsg = urlConnection.getResponseMessage();
urlConnection.disconnect();
Log.d(TAG, "Code: " + serverResponse + " - Menssage: " + serverMsg);
Have a good day, for 2 days I can not solve the problem.
took the app is very similar to that
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
everything works well, I get the GPS coordinates.
process would then obtain the coordinates + sending them to the server to be moved to a background service and that there was a problem, come coordinates 0.0 0.0
MainActivity.java (its all workin)
public class MainActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
final String LOG_TAG = "myLogs";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.button1);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
// #/mygps.php?lat=33.995834&lon=22.93707×tamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0
new RequestTask().execute("http://map.domain.ru/mygps.php?lat="+latitude+"&lon="+longitude+"×tamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0");
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
public void onClickStart(View v) {
startService(new Intent(this, MyService.class));
}
public void onClickStop(View v) {
stopService(new Intent(this, MyService.class));
}
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
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 = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
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;
// First get location from Network Provider
if (isNetworkEnabled) {
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
public class MyService extends Service {
final String LOG_TAG = "myLogs";
// GPSTracker class
GPSTracker gps;
MyBinder binder = new MyBinder();
Timer timer;
TimerTask tTask;
long interval = 10000;
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "onCreate");
// timer = new Timer();
// schedule();
}
public void schedule() {
if (tTask != null) tTask.cancel();
if (interval > 0) {
tTask = new TimerTask() {
public void run() {
Log.d(LOG_TAG, "run");
gps = new GPSTracker(getApplicationContext()); // also tried MyService.this
if(gps!=null){
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.d(LOG_TAG, "geo"+latitude+" lon"+longitude);
new RequestTask().execute("http://map.domain.ru/mygps.php?lat="+latitude+"&lon="+longitude+"×tamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0");
}
}else{
Log.d(LOG_TAG, "GPS null");
}
}
};
timer.schedule(tTask, 10000, interval);
}
}
long upInterval(long gap) {
interval = interval + gap;
schedule();
return interval;
}
long downInterval(long gap) {
interval = interval - gap;
if (interval < 0) interval = 0;
schedule();
return interval;
}
// public IBinder onBind(Intent arg0) {
// Log.d(LOG_TAG, "MyService onBind");
// return binder;
// }
class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
//}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
// someTask();
timer = new Timer();
schedule();
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
super.onDestroy();
Log.d(LOG_TAG, "onDestroy");
// stopSelf();
timer.cancel();
}
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "onBind");
return null;
}
void someTask() {
}
}
Why in the last class instead coordinates come nulls
code
Log.d(LOG_TAG, "geo "+latitude+" lon "+longitude);
write log "geo 0.0 lon 0.0"
this is because on that time gps cannot get location
almost the time when you are in building this happened
and there isnt lastknown location
you just checked that gps enabled
after that you must confident about the location that returned by checking location timestamp by difference between device time and location timestamp