I found a project in github about location tracker.and I want to change it.
How do it work?
You install this application in your device.
and from another device you send a message to your device (your message must be Where are you?)(that device that you installed application before). when you send this message , after 1 minutes you receive a link that show the current location.
https://github.com/quentin7b/android-location-tracker(link of project)
Now I want to send any message . not limited to send just where are you?
Now I want to get string from user to save and then compare then IF there are equal send the location link.
In this activity I must get string to save.
here is the code:
public class LocationTrackerActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and here :
public class SMSReceiver extends BroadcastReceiver
{
LocationManager lm;
LocationListener locationListener;
String senderTel;
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message that was received---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str="";
if (bundle != null)
{
senderTel = "";
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if (i==0) {
//---get the sender address/phone number---
senderTel = msgs[i].getOriginatingAddress();
}
//---get the message body---
str += msgs[i].getMessageBody().toString();
}
if (str.startsWith("Where are you?")) {
//---use the LocationManager class to obtain locations data---
lm = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
//---request location updates---
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
60000,
1000,
locationListener);
//---abort the broadcast; SMS messages won’t be broadcasted---
this.abortBroadcast();
}
}
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
//---send a SMS containing the current location---
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(senderTel, null,
"http://maps.google.com/maps?q=" + loc.getLatitude() + "," +
loc.getLongitude(), null, null);
//---stop listening for location changes---
lm.removeUpdates(locationListener);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
}
}
in this code it compare with Where are you ?
if (str.startsWith("Where are you?")) {
//---use the LocationManager class to obtain locations data---
lm = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
//---request location updates---
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
60000,
1000,
locationListener);
The point is that I am new with android. I don't which key word help me to search about my problem can help me.
please help
thanks in advance
Related
I am able to send the location (String address) + messages to my server; however, my app crashed after sending data to server. I used Volley library to make a POST request. Can someone help me fix this issue?
First I get the location and the list of the address.
public class MainActivity extends AppCompatActivity {
//Declare LocationManager and LocationListener
LocationManager locationManager;
LocationListener locationListener;
String address = "Unable to get the address!";
EditText Message;
AlertDialog.Builder builder;
String server_url ="https://schoolserver-tand089.c9users.io/Report.php";
//Process when users give the permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Start the location service
startListening();
}
}
//Checking permission granted method
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
//Update location method. 1 variable location
public void updatedLocationInfo(Location location) {
Log.i ("Location", location.toString());
//Cast the textViews
TextView latTextView = (TextView) findViewById(R.id.txtLat);
TextView lonTextView = (TextView) findViewById(R.id.txtLong);
TextView altTextView = (TextView) findViewById(R.id.txtAltitude);
TextView accTextView = (TextView) findViewById(R.id.txtAccuracy);
//get the string from location
latTextView.setText("Latitude: " + location.getLatitude());
lonTextView.setText("Longitude: " + location.getLongitude());
altTextView.setText("Altitude: " + location.getAltitude());
accTextView.setText("Accuracy: " + location.getAccuracy());
//Create Geocoder object to Get the address
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
//Using try/catch to prevent the app from crashing when failing to get Addresses
try {
//Declare the error string
//String address = "Unable to get the address!";
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
//Check if the address is valid
if (listAddresses != null && listAddresses.size() > 0) {
//Set address to empty string again when we know it is working
address = "Address: \n";
// Log.i("Address", listAddresses.get(0).toString());
//check for every item in the list Addresses is valid
if (listAddresses.get(0).getSubThoroughfare() != null) {
address += listAddresses.get(0).getSubThoroughfare() + " ";
}
//Street name
if (listAddresses.get(0).getThoroughfare() != null) {
address += listAddresses.get(0).getThoroughfare() + "\n";
}
//City name
if (listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + "\n";
}
//Zip code
if (listAddresses.get(0).getPostalCode() != null) {
address += listAddresses.get(0).getPostalCode() + "\n";
}
//Country name
if (listAddresses.get(0).getCountryName() != null) {
address += listAddresses.get(0).getCountryName() + "\n";
}
TextView addressTextView = (TextView) findViewById(R.id.txtAddress);
//set the address into the text View
addressTextView.setText(address);
//Log.i("Address", address.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up locationManager and locationListener above and cast them into their type
//Using built-in location service
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
//Get the location when it changes
#Override
public void onLocationChanged(Location location) {
//call the updated location above
updatedLocationInfo(location);
}
//
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Check for the version of SDK
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
// above 23 we need to check for permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//ask for permission. Number 1 is just a request queue.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
//we have permission
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//Get the last location from the built-in GPS
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//In case location does not have lastknownlocation, we call the updatedLocation method above
if (location != null) {
updatedLocationInfo(location);
}
}
}
}
Next, I used the onClick method to send the Address and a message to server when user clicks the button.
// using onClick
public void bntTap (View bnt) {
Message = (EditText) findViewById(R.id.message);
//Hide virtual keyboard after click the button
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
final String message;
message = Message.getText().toString();
if (message.equals("")) {
builder.setTitle("Unable to report");
//Creating a AlertDialog to display errors
AlertDialog alertDialog = builder.create();
alertDialog.setMessage("Please Enter All Required Fields*");
alertDialog.show();
} else {
//Post request
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//get response form server to check if it is successfully submitted
builder.setTitle("Server Response");
builder.setMessage("Congratulation" + " " + response);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Message.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//send data to mySQL server
//the keys must be same as field names in mySQL server
// get the list of the address
params.put("LOCATION", address);
params.put("MESSAGES", message);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addTorequestqueue(stringRequest);
//Log.i("Address", address.toString());
}
}
All the data successfully sent to the server, but the app crashed.
Updated: logcat when crashing
logcat when crashing
You are getting an NPE, as you forgot to define builder. You have only declared it in your code as
AlertDialog.Builder builder;
Please define the builder as
builder = new AlertDialog.Builder(MainActivity.this);
in your onCreate().
I have an issue, I need to get the latitude and longitude of one specific moment like taking a picture. I get the Double values, the problem is that they're always 0. I receive no exceptions, and the coordinates are uploaded successfully to Firebase Database, but when I check them in the JSON, they are always zero (I took like 20 pictures).
This is my sections code of "location" stuffs and the uploading to Firebase Database.
My Main Activity is like this.
public class MainActivity extends AppCompatActivity implements LocationListener
Global variables related to Location
double latitude;
double longitude;
This goes inside onCreate():
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String networkProvider = LocationManager.NETWORK_PROVIDER;
String gpsProvider = LocationManager.GPS_PROVIDER;
final Location location= new Location(networkProvider);
onLocationChanged(location);{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(gpsProvider, 5000, 10, this);
This goes in a button onClickListener(), also inside onCreate() method.
//Insert coordinates to JSON Firebase database...
Coordinates coordinates = new Coordinates();
coordinates.setLatitude(location.getLatitude());
coordinates.setLongitude(location.getLongitude());
testReference.push().setValue(coordinates);
Toast.makeText(MainActivity.this, "Coordinates uploaded!", Toast.LENGTH_LONG).show();
Also I have these methods inside MainActivity:
#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) {
}
Try this:
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
if(providerName!=null)
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
and Implement Your Location Listener class:
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
location = loc;
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
check null value for getLastKnownLocation() method..
i am making a app that tracks the user and tracks another user which in theory would be an animal.
my app goes like this, you register a username and pass then when this is done the user can log into the map by reentering the correct username and password. This is where the issues begin.
upon creation of the screen the map loads with the users current location and auto sends a sms to the "animals" phone to request gps details, this then sends back 2 sms messages, 1 containing the gps information. i have a SmsReceiver class which reads this information and extracts the longitude and latitude data, converts it into a double then passes it to the map activity to be converted into a lnglat variable and displayed on the google map with a marker. Now the issue i am having is that it can take several minutes for the sms to return with the gps information, when this is done and the intent is used to send the coordinates to the map page a button must be clicked so that the longitude and latitude are combined into the AnimalCoordinate and the marker is shown, however because og the time gap its imposible to press the button at the same time the sms is retrieved and it causes a crash as the data is being sent from the smsreceiver class to nothing on the other side, and if i take the intent out of the onclick method the same thing happens but in reverse, the map runs the intent but the informaion is not there yet and it crashes.
any help would be greatly appreciated as this has been a nightmare.
i am also sorry if i overcomplicated the explanation, i wanted to ake sure it was explained as best i could.
the code is below for the two classes.
Map class
public class MainScreen extends FragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private String provider;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
map = ((SupportMapFragment)getSupportFragmentManager().
findFragmentById(R.id.map)).getMap();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(this, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
// Sets the map type to be "hybrid"
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Bundle b = getIntent().getExtras();
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(this, "Location " + lat+","+lng,
Toast.LENGTH_LONG).show();
LatLng Usercoordinate = new LatLng(lat, lng);
Marker User = map.addMarker(new MarkerOptions()
.position(Usercoordinate)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//Move the camera instantly to user with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Usercoordinate, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
//Sends sms to 'animal phone'
String phoneNo = "***********";
String sms = "GPSLocation";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void map_help(View view) {
//method for the help button
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Help");
// set dialog message
alertDialogBuilder
.setMessage("Click the 'Pet' button to display the pets location." +
"This can take a few minutes to retrieve.")
.setCancelable(false)
.setPositiveButton("ok",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
};
public void Find_Pet(View view)
{
//String phoneNo = "07516909014";
// String sms = "GPSLocation";
// try {
// SmsManager smsManager = SmsManager.getDefault();
//smsManager.sendTextMessage(phoneNo, null, sms, null, null);
//Toast.makeText(getApplicationContext(), "SMS Sent!",
// Toast.LENGTH_LONG).show();
// } catch (Exception e) {
// Toast.makeText(getApplicationContext(),
// "SMS faild, please try again later!",
//Toast.LENGTH_LONG).show();
// e.printStackTrace();
//}
}
public void Show_Pet(View view)
{
//gets coordinates from SmsReceiver
Bundle b = getIntent().getExtras();
double AnimalLat = b.getDouble("key");
Bundle d = getIntent().getExtras();
double AnimalLon = d.getDouble("key1");
LatLng Animalcoordinate = new LatLng(AnimalLat, AnimalLon);
//adds pets marker on map
Marker Animal = map.addMarker(new MarkerOptions()
.position(Animalcoordinate)
.title("Your pet is here")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
SmsReceiver class
public class SmsReceiver extends BroadcastReceiver
{
String lat = null;
String lon = null;
String message = null;
final SmsReceiver context = this;
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += msgs[i].getMessageBody().toString();
}}
message = str.toString();
String[] test = message.split("");
char[] test2 = test[1].toCharArray();
//if the first character of the sms is C then read gps information
if (test2[0] == 'C' || test2[0] =='c')
{
lat = message.substring(45, 56);
lon = message.substring(67, 78);
double AnimalLat=Double.parseDouble(lat);
double AnimalLon=Double.parseDouble(lon);
//Pass coordinates to MainScreen
Intent a = new Intent(getApplicationContext(), MainScreen.class);
Bundle b = new Bundle();
b.putDouble("key", AnimalLat);
a.putExtras(b);
startActivity(a);
Intent c = new Intent(getApplicationContext(), MainScreen.class);
Bundle d = new Bundle();
d.putDouble("key1", AnimalLon);
c.putExtras(d);
startActivity(c);
}else {
}
}
private void startActivity(Intent a) {
// TODO Auto-generated method stub
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}}
I also want to apologize for the layout of the code, this is the first time i have pasted code on this site.
Thanks again.
To be honest, I'm not sure which Button you are talking. The only one I saw was in the AlertDialog unless I missed something. Anyway, you can disable your Button until whatever data has a value or you can do nothing in the onClick() if it is null
//inside your Button
if (data != null)
{
...do stuff in here
}
If you need more clarification then please indicate in the code the data you are talking about and the Button but I think you get the idea.
i have a problem. When i test this. and i ask for the showCurrentLocation function it always returns null. It works in the emulator when i send the location after. But i need this to work on the phone, and there you can't send the location like in de DDNS window.
Here's my code
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
protected Button stopLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
/*stopLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//locationManager.removeUpdates(MyLocationListener) ;
}
}); */
}
public String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
protected void showCurrentLocation() {
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(crit, true);
Location loc = locationManager.getLastKnownLocation(provider);
if (loc != null) {
String longi = "" + loc.getLongitude();
String lat = "" + loc.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
longi,
lat,
num );
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
if (loc == null)Toast.makeText(LbsGeocodingActivity.this, "Null ",
Toast.LENGTH_LONG).show();
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
String longi = "" + loc.getLongitude();
String lat = "" + loc.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
longi,
lat,
num );
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
My permissions are: FINE_LOCATION COURSE_LOCATION.
I really just want it that it tracks the users location, even on the background..
You can sent mock locations also to your Android device see
Android mock location on device?
Then besides that I had this problem too it seems it maybe never had a location before on your device try to open google maps and make sure you get located and then try again. Also I suspected something like first time you use the application you don't have access to a last know location yet because you never used it so you first need to get located and next time you startup the application it will work. If you want a quick location try to get located by wifi or cell towers
And make sure the permissions are set!
did you checked the GPS is switched on in your phone, after switching on GPS it will take some time to get the location updates.
How do I get the current Latitude and Longitude of the mobile device in android using location tools?
Use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
Here is the class LocationFinder to find the GPS location. This class will call MyLocation, which will do the business.
LocationFinder
public class LocationFinder extends Activity {
int increment = 4;
MyLocation myLocation = new MyLocation();
// private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intermediat);
myLocation.getLocation(getApplicationContext(), locationResult);
boolean r = myLocation.getLocation(getApplicationContext(),
locationResult);
startActivity(new Intent(LocationFinder.this,
// Nearbyhotelfinder.class));
GPSMyListView.class));
finish();
}
public LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
double Longitude = location.getLongitude();
double Latitude = location.getLatitude();
Toast.makeText(getApplicationContext(), "Got Location",
Toast.LENGTH_LONG).show();
try {
SharedPreferences locationpref = getApplication()
.getSharedPreferences("location", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = locationpref.edit();
prefsEditor.putString("Longitude", Longitude + "");
prefsEditor.putString("Latitude", Latitude + "");
prefsEditor.commit();
System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// handler for the background updating
}
MyLocation
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show();
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 10000);
// Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
With google things changes very often: non of the previous answers worked for me.
based on this google training here is how you do it using
fused location provider
this requires Set Up Google Play Services
Activity class
public class GPSTrackerActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();
}
} catch (SecurityException e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
usage
in you activity
Intent intent = new Intent(context, GPSTrackerActivity.class);
startActivityForResult(intent,1);
And this method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
Double longitude = extras.getDouble("Longitude");
Double latitude = extras.getDouble("Latitude");
}
}
you can got Current latlng using this
`
public class MainActivity extends ActionBarActivity {
private LocationManager locationManager;
private String provider;
private MyLocationListener mylistener;
private Criteria criteria;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default
// user defines the criteria
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
String a=""+location.getLatitude();
Toast.makeText(getApplicationContext(), a, 222).show();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// Initialize the location fields
Toast.makeText(MainActivity.this, ""+location.getLatitude()+location.getLongitude(),
Toast.LENGTH_SHORT).show()
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
Toast.LENGTH_SHORT).show();
}
}
`
Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat;
double lng;
LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
}else{
geocoder = new Geocoder(activity);
try {
user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
lat=(double)user.get(0).getLatitude();
lng=(double)user.get(0).getLongitude();
System.out.println(" DDD lat: " +lat+", longitude: "+lng);
}catch (Exception e) {
e.printStackTrace();
}
}
Best way is
Add permission manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then you can get GPS location or if GPS location is not available then this function return NETWORK location
public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
LocationManager lm = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
assert lm != null;
isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location networkLoacation = null, gpsLocation = null, finalLoc = null;
if (isGpsEnabled)
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkLocationEnabled)
networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null && networkLoacation != null) {
//smaller the number more accurate result will
if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
return finalLoc = networkLoacation;
else
return finalLoc = gpsLocation;
} else {
if (gpsLocation != null) {
return finalLoc = gpsLocation;
} else if (networkLoacation != null) {
return finalLoc = networkLoacation;
}
}
return finalLoc;
}
You can use FusedLocationProvider
For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
...
...
...
implementation 'com.google.android.gms:play-services-location:17.0.0'
}
Permissions in Manifest
Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_ID
)
Then you can use the FusedLocationProvider Client to get the updated location in your desired place.
mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
var location: Location? = task.result
if (location == null) {
requestNewLocationData()
} else {
findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
}
}
You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality.
If there is no cache location then it will catch the current location using:
private fun requestNewLocationData() {
var mLocationRequest = LocationRequest()
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
mLocationRequest.interval = 0
mLocationRequest.fastestInterval = 0
mLocationRequest.numUpdates = 1
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mFusedLocationClient!!.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
)
}
Plug and play location-manager that can be used both in XML-based projects and Jetpack Compose projects (personally using it in JetpackCompose)
class LocationManager(context: Context): LocationCallback() {
val context = context
var publicCompletion: ((Double, Double) -> Unit)? = null
var fusedLocationProviderClient = FusedLocationProviderClient(
context
)
fun requestLocationPermission() {
val activity = context as Activity?
ActivityCompat.requestPermissions(
activity!!,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION
),
101
)
}
fun checkIfLocationPermissionIsGranted(): Boolean {
return (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
)
}
fun getLatitudeLongitude(completion: (Double, Double) -> Unit) {
publicCompletion = { latitude, longitude ->
completion(latitude, longitude)
}
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
val activity = context as Activity?
fusedLocationProviderClient.lastLocation.addOnCompleteListener(activity!!) { task ->
var location: Location? = task.result
if (location != null) {
publicCompletion?.let { it(location!!.latitude, location!!.longitude) }
} else {
requestLocationUpdates()
}
}
}
}
fun requestLocationUpdates() {
var request = LocationRequest()
request.priority = com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY
request.fastestInterval = 0
request.numUpdates = 1
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
fusedLocationProviderClient.requestLocationUpdates(
request, this, Looper.myLooper()
)
}
}
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
publicCompletion?.let { it(p0!!.lastLocation!!.latitude, p0!!.lastLocation!!.longitude) }
}
override fun onLocationAvailability(p0: LocationAvailability?) {
super.onLocationAvailability(p0)
}
}
Just follow Google recommendation and prepared codes in kotlin: (Supports also Android 11 and 12):
https://github.com/googlecodelabs/while-in-use-location
and its step by step explanation:
https://codelabs.developers.google.com/codelabs/while-in-use-location