This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
This activity has 2 button, Start and Stop. When button start clicked, its save
user location to firebase and button stop to stop it. So, I use LocationManager.requestLocationUpdates to make every 5 second user location inserted to firebase. But this makes my app crash, here is my code
package com.example.julio.firebasemaster;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView condition;
Button start;
Button stop;
DatabaseReference mDatabase;
DatabaseReference mChild;
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
mChild = mDatabase.child("user");
start = (Button) findViewById(R.id.btnStart);
stop = (Button) findViewById(R.id.btnStop);
permission();
start.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("MissingPermission")
#Override
public void onClick(View view) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
permission();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = (new LocationListener() {
#Override
public void onLocationChanged(Location location) {
String latitude = location.getLatitude() + " ";
String longitude = location.getLongitude() + " ";
HashMap<String, String> data = new HashMap<>();
data.put("latitude", latitude);
data.put("longitude", longitude);
mChild.setValue(data);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locationManager.removeUpdates(locationListener);
}
});
}
private void permission() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
}
The Crush occur when I click start button
I'm using firebase assistant, so there is no problem with the initialization
Help me please, my head want to explode thinking this bug :(
Add null check inside onLocationChanged
public void onLocationChanged(Location location) {
if (location != null) {
String latitude = location.getLatitude() + " ";
String longitude = location.getLongitude() + " ";
HashMap<String, String> data = new HashMap<>();
data.put("latitude", latitude);
data.put("longitude", longitude);
mChild.setValue(data);
}
}
I hope this will help you
Related
I have been trying to get location via gps through the following code. I get the updates when i change the provider to NETWORK_PROVIDER, but i dont receive any data or location when i use GPS_PROVIDER.
I have referred the following tutorials-
http://www.viralandroid.com/2015/12/how-to-get-current-gps-location-programmatically-in-android.html
and
https://www.youtube.com/watch?v=QNb_3QKSmMk
package app.com.example.android.locationapp;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView lat, longi;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat = (TextView) findViewById(R.id.textView2);
longi = (TextView) findViewById(R.id.textView4);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Please enable location permission", Toast.LENGTH_SHORT).show();
return;
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Log.i("MainActivity", "reqLocationUpdates() method called");
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("MainActivity","onLocation executed");
lat.setText(location.getLatitude() + "");
longi.setText(location.getLongitude() + "");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
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
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(this);
}
}
Make sure you have fine location permission set. And make sure you're doing runtime permissions checks. But most likely your problem is LOS to satellites. If you're testing indoors, you probably can't get the satelite signal. Without that, you can't figure out your location and it will never call you. Go outside to test and see if it works.
I am new to android and try to implement an activity with two tab one show co-ordinates which i got from GPS-Service and i want to mark that current location (co-ordinates value using marker) in map using coordinates value which i got from GPS services. And kindly help me for implementing Geo Fencing in map also.
GPS Service
package com.app.servicegps;
/**
* Created by Android on 29-Dec-16.
*/
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinatesLongt",location.getLongitude());
i.putExtra("coordinatesLangt",location.getLatitude());
sendBroadcast(i);
}
#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);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Map Activity
package com.app.servicegps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener,OnMapReadyCallback,
SensorEventListener, DialogInterface.OnClickListener {
private GoogleMap mMap;
private BroadcastReceiver broadcastReceiver;
Marker now;
String langt = null;
String longt= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
//TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
//double latitude = location.getLatitude();
// Getting longitude of the current location
// double longitude = location.getLongitude();
double latitude= Double.parseDouble(langt);
double longitude= Double.parseDouble(longt);
// Creating a LatLng object for the current location
// LatLng latLng = new LatLng(latitude, longitude);
LatLng latLng = new LatLng(latitude, longitude);
now = mMap.addMarker(new MarkerOptions().position(latLng));
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//get value
if(intent.getAction().equals("location_update"))
{
langt=intent.getStringExtra("coordinatesLangt");
longt=intent.getStringExtra("coordinatesLongt");
}
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
/* LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Main Activity
package com.app.servicegps;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn_start, btn_stop;
private TextView textView;
private BroadcastReceiver broadcastReceiver;
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.append("\n" +intent.getExtras().get("coordinates"));
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.button);
btn_stop = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);
if(!runtime_permissions())
enable_buttons();
}
private void enable_buttons() {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}
}
Kindly help me for Geo fencing how i implement it it map activity.
The basic this i want is a main activity with tabs fragments.
Fragment 1st - Show Coordinates
Fragment 2nd Show Map
And A Geo Fencing To Show Notification when i enter in a tag place.
Interface class
public interface LocationInter {
void onUpdateLocation(Location location);
}
Implement the interface in main activity.
Add below lines in GPS service class.
private static LocationInter locationListener = null;
public void LocationInstance(LocationGuideInter locationListeners) {
if (locationListener == null) {
locationListener = locationListeners;
}
}
In Location change add this line
if (locationListener != null) {
locationListener.onUpdateLocation(location);
}
This is taken from android documentation so you can look at more details here
Set up for Geofence Monitoring
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Create geofence objects
Use Geofence.Builder to create a geofence, setting the desired radius, duration, and transition types for the geofence. For example, to populate a list object named mGeofenceList:
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
Specify geofences and initial triggers
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
Define an Intent for geofence transitions
public class MainActivity extends FragmentActivity {
...
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
Add geofences
public class MainActivity extends FragmentActivity {
...
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);
}
Handle Geofence Transitions
public class GeofenceTransitionsIntentService extends IntentService {
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
List triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type,
geofenceTransition));
}
}
Geofences tutorial from Raywendrlich here
For some reason it only updates the textviews when the app hits onPause, like when I hit the home button, or multitasking button. Can someone help me figure out why that is?
MainActivity.java:
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private String lat, lon;
private TextView longTextView, latTextView;
LocationService locationService = new LocationService(this);
private Intent intentService;
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latTextView = (TextView) findViewById(R.id.latitude_textview);
longTextView = (TextView) findViewById(R.id.longitude_textview);
}
#Override
protected void onStart() {
super.onStart();
locationService.buildGoogleApiClient();
locationService.apiConnect();
if (latTextView != null && longTextView != null) {
latTextView.setText( locationService.getLat());
longTextView.setText( locationService.getLon());
Toast.makeText(getApplicationContext(), " Actually got location", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "The shit was null fam", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onStop() {
super.onStop();
locationService.apiDisconnect();
}
}
LocationService.java:
import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import static com.google.android.gms.wearable.DataMap.TAG;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// ============================================================= Variables
Context context;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String lat, lon;
final static String[] LOCATION_PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long UPDATE_FASTEST_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static boolean isEnded = false;
public static Boolean requestingLocationUpdates;
protected String lastUpdateTime;
final int GOOGLEAPI_REQUEST_CODE = 24;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
// ============================================================= Constructor
public LocationService(Context context) {
this.context = context;
}
// ============================================================= Getters / Setters
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
// ============================================================= Methods
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void apiConnect() {
mGoogleApiClient.connect();
}
public void apiDisconnect() {
mGoogleApiClient.disconnect();
}
void updateUI() {
}
// ============================================================= Implemented Location Methods
#Override
public void onLocationChanged(Location location) {
setLat(String.valueOf(location.getLatitude()));
setLon(String.valueOf(location.getLongitude()));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets Location to update every second
mLocationRequest.setFastestInterval(UPDATE_FASTEST_INTERVAL_IN_MILLISECONDS); // The fastest location can update is every half-second
startLocationUpdates();
// TODO come back to this to see whats up
/* mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);*/
if (mLastLocation != null) {
setLat(String.valueOf(mLastLocation.getLatitude()));
setLon(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
protected void startLocationUpdates() {
/*if (!requestingLocationUpdates) {
requestingLocationUpdates = true;*/
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) context, LOCATION_PERMISSIONS, GOOGLEAPI_REQUEST_CODE);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
Log.i(TAG, " startLocationUpdates===");
isEnded = true;
//}
}
// ============================================================= Implemented Service Methods
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
Log.d("LOC", "Service init...");
isEnded = false;
requestingLocationUpdates = false;
lastUpdateTime = "";
buildGoogleApiClient();
if (mGoogleApiClient.isConnected() && requestingLocationUpdates) {
startLocationUpdates();
}
return Service.START_REDELIVER_INTENT;
}
}
The reason why you are not getting the location updated in textview is because your code doesn't have a way for the service to communicate back to the activity.
If you want to obtain location only when the activity is in foreground don't use Service and please look into this google's example for obtaining location and updating on a TextView using fused location provider.
I am not sure why you are using a Service.Use Service only when you want to continuously fetch the location even when the app is running background.
For this use any one of the method mentioned here to inform the activity that a new location has been obtained.LocalBroadcast would be your best bet. Anyway explore the best possible solution that suits your usecase in the previous link.
I have an application and I want to use the GPS's Location. After implementing what I was taught, I have two files, VirtualAssistantActivity which uses the LocationGPS file. The second file will send the result with an intent received from the first file.
The problem is the TextView that is supposed to be edited after receiving the intent filled with the location.toString() doesn't change. After using the debug feature of Android Studio, I've found that it's like the locationManager's requestLocationUpdate is never called, I can't even get into the new LocationListener's creation.
I am using a Sony XPERIA running Android 5.0, and decided to develop targeting Android 4.0 with API 15.
Here's the VirtualAssistantActivity code :
public class VirtualAssistantActivity extends AppCompatActivity {
private LocationGPS lgps = null;
private BroadcastReceiver mLocationReceiver;
private TextView tvTest = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_virtual_assistant);
tvTest = (TextView) findViewById(R.id.tV_testGeo);
lgps = LocationGPS.get(this.getApplicationContext());
mLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent){
Location l = (Location)intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
if (l!=null){
tvTest.setText(""+l);
} else {
tvTest.setText("Empty intent");
}
}
};
}#Override
protected void onResume(){
super.onResume();
this.registerReceiver(mLocationReceiver, new IntentFilter(LocationGPS.ACTION_LOCATION));
lgps.startLocationUpdates();
Toast.makeText(getApplicationContext(), "BR Init", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
//unregisterReceiver(mLocationReceiver);
}
And the LocationGPS's :
public class LocationGPS {
static LocationGPS slocationGPS = null;
Context mAppContext = null;
LocationManager mLocationManager = null;
public static String ACTION_LOCATION = "LOCATION_MSG";
private LocationGPS(Context appContext) {
mAppContext = appContext;
mLocationManager = (LocationManager)appContext.getSystemService(Context.LOCATION_SERVICE);
}
public static LocationGPS get(Context c) {
if (slocationGPS == null) {
slocationGPS = new LocationGPS(c);
}
return slocationGPS;
}
private void broadcastLocation(Location location) {
Intent broadcast = new Intent(this.ACTION_LOCATION);
broadcast.putExtra(LocationManager.KEY_LOCATION_CHANGED, location);
this.mAppContext.sendBroadcast(broadcast);
}
public void startLocationUpdates(){
if (ContextCompat.checkSelfPermission(mAppContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mAppContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.requestLocationUpdates
(LocationManager.GPS_PROVIDER, 1000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
//Log.d(this.getClass().getName(), location.toString());
Log.d("GPS", "Latitude " + location.getLatitude() + " et longitude " + location.getLongitude());
Toast.makeText(mAppContext, "Location", Toast.LENGTH_SHORT).show();
broadcastLocation(location);
}
Toast.makeText(mAppContext, "Location", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
I've searched for some solutions, and while it seems to work for everyone, or at least they have some error messages, I don't know what I can do except eventually use Google's APIs, but I would prefer to avoid that. I have checked my permission, they're granted and this is a list of my imports:
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
And the permissions :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
i recently asked a question for implementation of toast message when the GPS is not enabled.
of this i knew it was possible.
Is it possible to automatically activate the GPS function in the background.
When i remotely activate the application in the background. can i activate the GPS from the phone itself aswell without the other phone reporting anything to the user ?
the situation is like this.
we have a project named ParentalControl Application. So a parent has to be able to track its child remotely.
does anyone have suggestion or ideas ... ?
if it is of anyhelp
this is the code i'm using at the moment.
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
TextView TxtLat;
TextView TxtLong;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TxtLat = (TextView) findViewById(R.id.TxtLat);
TxtLong = (TextView) findViewById(R.id.TxtLong);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// implementation of TOASTS
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast toast= Toast.makeText(MainActivity.this, " You can improve the accuracy by turning on the GPS", Toast.LENGTH_SHORT);
toast.show();
}
LocationListener ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class myLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
if (location != null)
{
double pLong = location.getLongitude();
double pLat = location.getLatitude();
TxtLat.setText(Double.toString(pLat));
TxtLong.setText(Double.toString(pLong));
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}