Change position GPS and TextView when phone is lock - android

I want to create app which will add new longitude and latitude every 3 second to the textview in scrollview. I have a problem with adding new coordinates when the phone is locked or app work in background
public class PomiarTrasy extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomiar_trasy);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
txt1.setText("Szukanie pozycji...");
} else {
txt1.setText("Twój GPS jest wyłączony");
}
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
txt1.setText("Szukanie pozycji...");
else
txt1.setText("Twój GPS jest wyłączony");
}
LocationManager lm;
Location savedLocation = null;
LocationListener locationListener = new LocationListener() {
#SuppressLint("MissingPermission")
#Override
public void onLocationChanged(Location location) {
String latitude = "";
String longitude = "";
if (location != null) {
latitude += location.getLatitude();
longitude += location.getLongitude();
txt1.setText("Uzyskano współrzędne!");
}
btn_start_zapis.setEnabled(true);
if (wlacz == 1) {
txt4.setText(txt4.getText() + "" + location.getLongitude() + ", " + location.getLatitude() + "\n");
txt5.setText(txt2.getText());
txt6.setText(txt3.getText());
txt2.setText(latitude);
txt3.setText(longitude);
}
if (savedLocation == null) {
savedLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
txt1.setText("Szukanie pozycji...");
}
#Override
public void onProviderDisabled(String s) {
txt1.setText("Twój GPS jest wyłączony");
}
};
Any sugestion how I can do it? I read about the Service - GPS work in background, but how do it with TextView?

Related

how do I update the latitude and longitude to the textview in android main activity having dependency injection with dagger 2

I am beginner in android. I am now learning dagger 2 dependency injection. I am coding an app which update the latitude and longitude to the textview screen. I don't know, how i would I update the location coordinates to the textview screen as i did the coding of onLocationChanged in the module class and I am injecting the class to the main activity.
I did the coding of getting the location update in LocationManager class.
I can show the updated coordinates using toast, but not able to change textview, is there any way to do this ?
The code in the main activity
public class MainActivity extends AppCompatActivity {
#Inject
LocationManager locationManager;
#InjectView(R.id.textView2)
TextView addressLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
MyApplication.inject(this);
locationManager.GetLocation();
}
}
I like to update the addressLocation textview with the coordinates that i am getting from LocationListener.
package com.test.xyz.daggersample1.service.impl;
public class LocationManager {
Geocoder geocoder;
List<Address> addresses;
private double lattitude = 0;
private double longitude = 0;
private Context context;
public LocationManager(Context context) {
this.context = context;
}
public String GetLocation() {
final String[] address = new String[1];
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return "";
}
geocoder = new Geocoder(context, Locale.getDefault());
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
lattitude = location.getLatitude();
// dialog.dismiss();
Toast.makeText(context, "Got the Longitude as " + longitude + " Lattitude as " + lattitude, Toast.LENGTH_SHORT).show();
**I like to pass these location values to the textview in the main activity**
try {
addresses = geocoder.getFromLocation(lattitude, longitude, 1);
address[0] = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "Got the Longitude as " + longitude + " Lattitude as " + lattitude, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(i);
}
};
locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 2000, 10, listener);
return address[0];
}
}
My project folder

Using Google Play location API in a seperated class?

In the Android Developer guide, Google showed how to use the Google Play Services API in an activity class. What is the best way to offload the API calls into a separate class?
public class GPSresource implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
public GPSresource(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
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;
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
The code I wrote above does not work since onConnected is never called since this is not an activity. Is there a better way to separate the GPS services from the Main Activity or is that the only option(If so, is there a reason as to why?) Perhaps making a thread in the main activity to run in the background?
Thanks!
onConnected is called, I made a mistake with reading the logs!
Here is an example :
public class LocationManager implements LocationListener {
private LocationManager locationManager;
public LocationManager()
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location mobileLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null)
{
onLocationChanged(mobileLocation);
}
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null)
{
onLocationChanged(netLocation);
}
}
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
//Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
// Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
// Log.e(TAG, "addr : " + addresses.toString());
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + s);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
public void pause() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
public void destroy() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
}

Issue in finding the lat and long in samsung S3

I am not getting the lat and long in samsung S3.In other devices my code is working fine and getting the proper lat and long.Below is my code to get the lat and long.
public class MainActivity extends Activity {
TextView textView1;
Location currentLocation;
double currentLatitude,currentLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
findLocation();
}
public void findLocation() {
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location,currentLatitude,currentLongitude);
Toast.makeText(
MainActivity.this,
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000)
.show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
void updateLocation(Location location,double currentLatitude,double currentLongitude) {
currentLocation = location;
this.currentLatitude = currentLocation.getLatitude();
this.currentLongitude = currentLocation.getLongitude();
textView1.setText(String.valueOf(this.currentLatitude) + "\n"
+ String.valueOf(this.currentLongitude));
}
}
In above code the onLocationChanged() method is not executing in S3 and the same code is not working in Samsung S3 device.In other devices it working fine.I am getting the correct lat and long in other devices.Please help me to sort out this problem..

How to use locationManager?

I try to add a location from the GPS but i always get null. Can you please help and show me what I did wrong?
I would like to always receive the location in onCreate. If no location is received
"No provider received" appears instead of the location. The problem is i always get the message.
//Location variables
private TextView gps;
private LocationManager locationManager;
private String locationProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_draw);
initializeData();
}
private void initializeData()
{
gps = (TextView) findViewById(R.id.GPS);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = locationManager.getBestProvider(new Criteria(), true);
if(locationProvider!=null)
{
gps.setText("Upload image location: "+ locationProvider);
}
else
{
gps.setText("Upload image location: No provider Found" );
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
private void showLocation(Location location)
{
if(location==null)
gps.append("\nUnknown location");
else
{
double lat = location.getLatitude();
double lng = location.getLongitude();
gps.append("\n\nLocation lat: " +lat+
", long: " + lng+"\n"
+ getAddress(lat, lng));
}
}
public void onLocationChanged(Location location) {
showLocation(location);
}
public void onProviderDisabled(String provider) {
gps.append("\nProvider Disabled: " +provider);
}
public void onProviderEnabled(String provider) {
gps.append("\nProvider Enabled: " +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
gps.append("\nProvider Status Changed: " + provider+ ",status: "+
status);
}
public String getAddress(double lat, double lng)
{
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String str = obj.getCountryName();
str+="\n" + obj.getCountryCode();
str+="\n" + obj.getLocality(); //current city
str+="\n" + obj.getAddressLine(0);
return str;
}
catch (IOException e) {
return "Error: " +e.getMessage();
}
}
1)You need to request updates from provider:
newLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, "error string");
2)Register a Listener:
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Do something
} );}

Location listener in android gives java.lang.IllegalArgumentException: listener==null

Hey While I am running the application it gives a error java.lang.IllegalArgumentException: listener==null , that tells that listener is null.
My sample code is here:
public class HelloAndroidGpsActivity extends Activity {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}
/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("mobile location manager is ="+locManager);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
locListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
System.out.println("mobile location is in listener1");
}
#Override
public void onProviderEnabled(String provider) {
System.out.println("mobile location is in listener2");
}
#Override
public void onProviderDisabled(String provider) {
System.out.println("mobile location is in listener3");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
System.out.println("after setting listener");
}
private void buttonGetLocationClick() {
getCurrentLocation();
System.out.println("mobile location is ="+mobileLocation);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n"
+ altitiude + "\n" + accuracy + "\n" + time);
} else {
editTextShowLocation.setText("Sorry, location is not determined");
}
}
}
Output in textbox is "Sorry, location is not determined""
If any one can tell me what is the problem then please help me.
Thank you
Initialize the listener before you use it.
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
At this point of time, locListener is null, and you are initializing it after this line of code. This may be the reason.
So rearrange the lines of your code like this;
locListener = new LocationListener() {...};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Hope this may help to solve your issue...

Categories

Resources