i want to get coordinat and i'm use function GPSTracker (follow tutorial https://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/) but any issue... i can't get coordinates, please help me guys
this is my acitivity :
public class InputDataSlo extends AppCompatActivity {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GPSTracker gps = new GPSTracker (InputDataSlo.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude= gps.getLongitude();
textView.setText("Latitude: "+latitude+" Longitude: "+longitude);
}else{
Toast.makeText(getApplicationContext(),
"Please cek permision", Toast.LENGTH_LONG)
.show();
}
}
});
}
This is file GPSTracker.java :
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude, longitude;
LocationManager locationManager;
AlertDialogManager am = new AlertDialogManager();
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
private Location getLocation() {
// TODO Auto-generated method stub
try {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
this.canGetLocation = true;
if (location == null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 3, this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} else {
showAlertDialog();
}
}catch(Exception e){
e.printStackTrace();
}
return location;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GPSTracker.this);
// 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?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// 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);
startActivity(intent);
dialog.cancel();
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void showAlertDialog(){
am.showAlertDialog(GPSTracker.this, "GPS Setting", "Gps is not enabled. Do you want to enabled it ?", false);
}
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;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
this.location = location;
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
My problem with access permissions row :
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 3, this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
Don't use GPSTracker. The code is broken- it will sometimes work, but its flawed at a design level. It confuses enabled with up and running, and doesn't account for the fact you can't always get locations. For a full explanation of all the ways its broken, see my blog at http://gabesechansoftware.com/location-tracking/ which also contains working code.
Also, you need runtime permissions (which aren't in my blog either, as it predates them). You'll need to add those in regardless.
Related
How to show the location permission pop up with an allow and a deny button?
I have function that receives the location, but now I need to go to the settings by myself and turn the location on.
I want that when the User opens the fragment, the location pop up gets shown.
This is the code I currently have:
LocationFinder class:
public class LocationFinder extends Service implements LocationListener {
Context context;
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 = 200 * 10 * 1; // 2 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public LocationFinder(Context context) {
this.context = context;
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) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) context
.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
// Log.e("Network-GPS", "Disable");
} 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.e("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
} else
// 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.e("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;
}
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(context);
alertDialog.setTitle("GPS settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
Fragment that shows location:
public class GarageFragment extends Fragment {
LocationFinder finder;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_garage, container, false);
getLocation();
return view;
}
public void getLocation() {
double longitude = 0.0;
double latitude = 0.0;
finder = new LocationFinder(getContext());
if (finder.canGetLocation()) {
latitude = finder.getLatitude();
longitude = finder.getLongitude();
// Toast.makeText(getActivity(), "lat-lng " + latitude + "--" + longitude, Toast.LENGTH_LONG).show();
} else {
finder.showSettingsAlert();
}
Geocoder gcd = new Geocoder(getContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
Toast.makeText(getActivity(), addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
} else {
// do your stuff
}
}
}
add this code to check your permission
if (ContextCompat.checkSelfPermission(Activity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(SplashActivity.this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(Activity.this, PERMISSIONS, 600);
} else {
// your code
}
add in your resultActivity
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.v("requestCode", "requestCode=" + requestCode);
switch (requestCode) {
case 600:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
case 700:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
}
}
Showing Location permission popup and turning location on are two different things.
You still have to go to setting to turn location on (if it's off), while permission is just allowing your app to use the location when it's on.
To get permission you can use this method RunTimePermissions.verifyStoragePermissions(getActivity());
public class RunTimePermissions {
// Storage Permissions variables
private static final int REQUEST_CODE = 6361;
private static String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
};
//persmission method.
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int locationPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
if (locationPermission != PackageManager.PERMISSION_GRANTED ) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS,
REQUEST_CODE
);
}
}
}
Add in manifests:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add in your activity:
public class MainActivity extends AppCompatActivity {
String[] locationPermissions= {"android.permission.ACCESS_COARSE_LOCATION","android.permission.ACCESS_FINE_LOCATION"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, locationPermissions, 121);
}
}
};
handler.postDelayed(runnable, 1000);
}
}
I'm new to android, don't know what I'm doing wrong
this class get longitude and latitude and sent to another class
the code is throwing an error onrequstpermission please tell me what to do how to do:
error on public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults
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) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Manifest.permission.ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good!
} else {
Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
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;
}
onRequestPermissionsResult is a method which should be outside the current method
public Location getLocation(){
//...code
if (ActivityCompat.checkSelfPermissio... ) {
// ERROR : cannot have function declaration inside another function
public void onRequestPermissionsResult(...) {
switch (requestCode) {//..code}
}
}
Note: you cannot have this in a Service class , you need some Activity to ask permission
ActivityCompat.OnRequestPermissionsResultCallback is implemented by FragmentActivity which is a parent of AppCompatActivity so it's not implemented by Service so you need to implement the runtime-permission code is some FragmentActivity | AppCompatActivity or you can check and show a notification (in case of no permission or probably a dialog) and redirect user to Activity to proceed with permission code.
Reference:
Implement runtime permission
I had a problem. I want to make an Android App for my Android Wear device. I want to get the latitude and longitude of my current location. But when I run the applicatie I got this error:
03-22 11:14:00.096 29013-29013/? E/AndroidRuntime: Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 52435096 byte allocation with 2097152 free bytes and 32MB until OOM
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
at java.lang.StringBuffer.append(StringBuffer.java:278)
at java.io.StringWriter.write(StringWriter.java:123)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
at java.io.PrintWriter.append(PrintWriter.java:691)
at java.io.PrintWriter.append(PrintWriter.java:687)
at java.io.Writer.append(Writer.java:198)
at java.lang.Throwable.printStackTrace(Throwable.java:324)
at java.lang.Throwable.printStackTrace(Throwable.java:300)
at android.util.Log.getStackTraceString(Log.java:343)
at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:61)
at com.android.internal.os.RuntimeInit.-wrap0(RuntimeInit.java)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:86)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
This is my code:
MainActivity.java
public class MainActivity extends Activity {
private TextView tvHuidigeLocatie;
private Button btSetHuidigeLocatie;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
onClickInfoButtonListener();
}
});
}
private void onClickInfoButtonListener() {
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
tvHuidigeLocatie = (TextView) stub.findViewById(R.id.tvHuidigeLocatie);
btSetHuidigeLocatie = (Button) stub.findViewById(R.id.btnSetHuidigeLocatie);
btSetHuidigeLocatie.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
tvHuidigeLocatie.setText("" + latitude + ", " + longitude);
}else{
gps.showSettingsAlert();
}
}
}
);
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context context;
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;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return location;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
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(context);
alertDialog.setTitle("GPS in settings");
alertDialog.setMessage("GPS staat niet aan, Wilt u naar uw instellingen gaan?");
alertDialog.setPositiveButton("Instellingen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#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) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I hope anyone see the problem and can help me with this problem.
android:largeHeap="true"
In your android manifest, hope this will solve your problem.
http://developer.android.com/guide/topics/manifest/application-element.html#largeHeap
I'm currently working on a project for school. I have to use location service. I have a marker problem. I can locate myself on the map with a small point from google (I think), but the marker is always on 0,0. If my logic is good, the getLatitude() and the getLongitude() return NULL. I've follow a tutorial for the code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
GPSTracker gps;
//ImageItem imgItem;
double lat;
double longi;
double latitude;
double longitude;
String adresse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
laCreation();
}
public void laCreation() {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation()==true) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
lat = latitude;
longi = longitude;
} else {
gps.showSettingsAlert();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
mMap.setMyLocationEnabled(true);
LatLng position = new LatLng(lat, longi);
mMap.addMarker(new MarkerOptions().position(position).title("Vous : "+ latitude + ","+longitude +"," +adresse));//new LatLng(lat,longi)
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
public void onMapReady(GoogleMap googleMap) {}
}
Here is my GPSTracker :
public class GPSTracker extends Service implements LocationListener {
private final Context context;
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; //10m avant update gps
private static final long MIN_TIME_BW_UPDATES = 2000; //2 sec avant uptade gps
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
onLocationChanged(location);
if (isGPSEnabled) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
if (latitude ==0){showSettingsAlert();}
}
}
}
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
if (latitude ==0){showSettingsAlert();}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
}
locationManager.removeUpdates(GPSTracker.this);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
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(context);
alertDialog.setTitle("GPS en cours de configuration");
alertDialog.setMessage("GPS non valide. Voulez-vous aller dans le menu de configuration?");
alertDialog.setPositiveButton("Configuration", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I'm French, sorry for my bad English
You should utilize method
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, location.getLatitude()+"-"+longitude = location.getLongitude());
// TODO Auto-generated method stub
}
for getting latitude and longitude. First time it will get definitely call and then it will be call and then as soon as location gets changed.
If you force fully asking for latti and longi their are chances OS is not having anything s it would return 0,0.
One way more ask for last known location using GoogleFuseLocationApi
public class SpotRecognistionService extends Service {
private static final String TAG = SpotRecognistionService.class.getSimpleName();
public static final String NOTIFICATION = "location.track.services.receiver";
//Google Api Client for Location
private GoogleApiClient mGoogleApiClient;
// private Location mLastLocation;
private LocationRequest mLocationRequest;
private GPSLocationListener gpsLocationListener;
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(gpsLocationListener)
.addOnConnectionFailedListener(gpsLocationListener)
.addApi(LocationServices.API)
.build();
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
gpsLocationListener = new GPSLocationListener();
buildGoogleApiClient();
//Connect to get Location
mGoogleApiClient.connect();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
private class GPSLocationListener implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
//Update Result
publishResults(location.toString(), 1);
}
private void publishResults(String lat_Long, int result) {
Log.i(TAG, lat_Long);
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
reConnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
reConnect();
}
public void reConnect() {
if (mGoogleApiClient != null && !mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
}
}
}
So I'm trying to update the current location of a user every 5 seconds using a locationMenager, but it's not working. Here the code:
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context context;
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;
private static final long MIN_TIME_BW_UPDATES = 5000;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.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);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
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(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
As you can see it is set to update. And this is the onCreate() in SearchActivity.java
gps = new GPSTracker(SearchActivity.this);
if (gps.canGetLocation()) {
ParseUser user2 = ParseUser.getCurrentUser();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
geoPoint = new ParseGeoPoint(latitude, longitude);
user2.put("lat_long", geoPoint);
textView.setText(latitude+" "+longitude);
user2.saveInBackground();
} else {
gps.showSettingsAlert();
}
So if I put the code above in a onClick method it works, it updates the current location. I've tried to implement it with a TimerTask but the location ends up being (0, 0). So does anyone know what I can do here? Because what preferably I would like to make a On/Off switch for the location, make it run in background if possible, but first I would like to resolve the issue with the Location Updates.
#Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
ParseUser user2 = ParseUser.getCurrentUser();
ParseGeoPoint geoPoint = new ParseGeoPoint(getLatitude(), getLongitude());
user2.put("lat_long", geoPoint);
user2.saveInBackground();
}
Okay so this was the answer, just had to change the onLocationChanged.