Hello could somebody help me with what i'm doing wrong.
I want this application to work in the background, i just want to make in a button where to stop the locationmanager. when i use the removeUpdates, its not working. I cant call that function there.
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 = 60000; // Minuten(van milliseconden) * aantal
protected LocationManager locationManager;
protected LocationListener locationListener;
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);
stopLocationButton = (Button) findViewById(R.id.stop_location_button);
LocationManager 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();
}
});
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LocationManager.removeUpdates(locationListener) ; }
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
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();
}
}
I really need this badly
Change the code from this (* indicates whats changed *):
***retrieveLocationButton***.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
locationManager.removeUpdates(locationListener) ;
}
});
To this:
stopLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
locationManager.removeUpdates(locationListener) ;
}
});
EDIT:
use locationManager "the global variable which starts with small letter" and not LocationManager "the class which starts with capital letter" for the function removeUpdates()
locationManager.removeUpdates(MyLocationListener);
try this.
Related
i am making a app in which on click of button it moves from 1 activity to 2nd activity on which i need gps to be active i used a alertdialog box to turn on the gps by clicking settings it will open to the setting and if i enable it dialogbox disapper and gps start working but if i press back button without enabling the gps it works and activity starts i want to check if gps is enabled if not the it should not show me the 2nd activity
No Error Coming but just on back press on setting without enabling it will start activity without any error and still gps is off.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView1 = (TextView) findViewById(R.id.location_view);
button1 = (Button) findViewById(R.id.camera);
button2 = (Button) findViewById(R.id.upload);
editText1 = (EditText) findViewById(R.id.remarks);
imageView11 = (ImageView) findViewById(R.id.image1);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
locationText = (TextView) findViewById(R.id.location_view);
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, (LocationListener) this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Logout");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Logout ");
alerDialogbuilder.setMessage("Logingout will need id password again");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intents = new Intent(Main3Activity.this,MainActivity.class);
startActivity(intents);
Toast.makeText(getApplicationContext(),"Successfull Logout",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Logout Canceled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
return true;
default:return super.onOptionsItemSelected(item);
}
}
private void camera(){
Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intents,CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST&&resultCode== Activity.RESULT_OK){
Bitmap photo= (Bitmap)data.getExtras().get("data");
imageView11.setImageBitmap(photo);
}
}
private void upload(){
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Upload ?");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Upload Data");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"File Uploading...",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Recheck Data",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
#Override
public void onClick(View view) {
if(view==button1){
camera();
}
else if (view == button2){
upload();
}
}
#Override
public void onLocationChanged(Location location) {
double lati = location.getLatitude();
double longi = location.getLongitude();
locationText.setText("Latitude: " + lati + "\n Longitude: " + longi);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Enable Gps to Continue");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("If You Want To Enable Gps Go To Settings");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
Toast.makeText(getApplicationContext(),"Enable Gps..",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
Toast.makeText(getApplicationContext(),"Uploading Failed,Enable Gps",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
}
i want to check only if gps is enabled or not when my activity start if it is not enabled go to settings and still if the user doesnot enable the gps setting it should not work any further pls help me out m a new to android
Implement below method for checking status -:
public boolean CheckGpsStatus() {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return GpsStatus;
}
protected LocationRequest locationRequest;
public void checkForLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setInterval(MIN_UPDATE_INTERVAL);
locationRequest.setNumUpdates(1);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public void checkForLocationSettings() {
try {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MainActivity.this);
settingsClient.checkLocationSettings(builder.build())
.addOnSuccessListener((Activity) MainActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// delay(1);
//Setting is success...
// Toast.makeText(SplashActivity.this, "Enabled the Location successfully. Now you can press the buttons..", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener((Activity) MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((Activity) MainActivity.this, GET_PERMISSION_REQ_CODE);
} catch (Exception ex) {
new MyUtils().catchError(MainActivity.this, ex);
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(MainActivity.this, "Setting change is not available.Try in another device.", Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
new MyUtils().catchError(MainActivity.this, e);
}
}
This Above code shows the popup for enable the gps if gps is not enabled and also gives you callback for success and failure
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{
protected static final String TAG = "MainActivity";
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
Marker mCurrLocationMarker;
GoogleMap mgooglemap;
private LocationManager locationManager;
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(latLng);
// markerOptions.title("Current Position");
// markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// mCurrLocationMarker = mgooglemap.addMarker(markerOptions);
//move map camera
mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
// locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();
//for you want to open Settings screen
while(!onProviderEnabled())
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
}
The onProviderDisabled() of the above code will provide you the required flow.
I have google searched this with no success and seams very strange to me.
I am building a simple GPS app that send co-ordinates with HttpRequest, though I have noticed when minimising the UI then maximising, It runs a duplicate of the same activity. and doubles up on HttpRequest's
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
processExtraData();
}
private void processExtraData() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, 5, this);
}
#Override
public void onLocationChanged(Location location) {
Bundle extras = getIntent().getExtras();
String driver_id = extras.getString("driverid");
String msg = "Driver:" + driver_id + "\nCurrent Location:\nLatitude: " + location.getLatitude()
+ "\nLongitude: " + location.getLongitude();
new HttpRequestTask(
new HttpRequest("https://www.autoflora.net/driver/gps.php?user_id=" + driver_id + "&latlong=" + location.getLatitude() + "*" + location.getLongitude(), HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
#Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
String s = calc.getText().toString();
calc.setText(s + "1")
TextView driver = (TextView) findViewById(R.id.driver);
driver.setText("" + driver_id);
TextView Longitude = (TextView) findViewById(R.id.longitude);
// Getting reference to TextView tv_latitude
TextView Latitude = (TextView) findViewById(R.id.latitude);
// Setting Current Longitude
Longitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
Latitude.setText("Latitude:" + location.getLatitude());
// Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
noticed when minimising the UI then maximising
There's neither minimising nor maximizing of UI on Android. You apparently start the activity again via launcher (this is most likely your maximizing thing) which creates new instance of you activity. If you want just single instance allowed no matter what, you must set system so by using android:launchMode in declaration of activity in your manifest file. See docs here for possible options.
#Override
public void onStart() {
super.onStart();
Toast.makeText(getBaseContext(), "start", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getBaseContext(), "resume", Toast.LENGTH_LONG).show();
locationcheck(); // checks permissions
}
#Override
public void onPause() {
super.onPause();
Toast.makeText(getBaseContext(), "pause", Toast.LENGTH_LONG).show();
}
#Override
public void onStop() {
super.onStop();
// locationManager.removeUpdates(this);
Toast.makeText(getBaseContext(), "stop", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(), "destroy", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
finish();
}
Seems to have fixed it..
I am currently making an application where I need to get the user's location when a button is clicked. I am using this sample and it works great as a sample application. My question is, how would I implement it into my application button's onClick event? I don't need it to refresh often, I just need it so that when the user clicks the button, it gets the user's latitude and longitude and saves them to two variables. What would be the best way to do this? I didn't post my own code because all I have is a button with an onClick event.
Follow these steps to get the location on button click:
Implement LocationListener in your activity like:
public class MainActivity Extends AppCompactActivity implements LocationListener
Then create an Instance For LocationManager, longitude, and latitude as below:
LocationManager locationManager; // create global outside all methods
Double currentLattitude, currentLongitude;
Set click event on your button as below:
btnLocation.setOnClickListner( new View.onClickListner
{
#Override
public void onClick(View v)
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
});
Now implement method for LocationListener as below:
#Override
public void onLocationChanged(Location location) {
currentLattitude = location.getLatitude();
currentLongitude = location.getLongitude());
}
#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");
}
With this, you can get your location via on click of your button.
Main thing to don't forget is to set permission (in your Manifest) as below:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Use fused location API this is the fastest from all others.
public class LocationActivity extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
LocationListener provides call back for location change through onLocationChanged.
GoogleApiClient.ConnectionCallbacks provides call back for GoogleApiClient onConnected.
GoogleApiClient.OnConnectionFailedListener provides call back for GoogleApiClient onConnectionFailed.
Source: http://javapapers.com/android/android-location-fused-provider/
I want to detect the switch of GPS.
My idea is to use IntentService and Broadcast intent.
My service is running but my broadcast receiver doesn't work.
I just wanna say to my HomeActivity if GPS is turn on/off by user. With this info, i will able to set up my GoogleMap with the current location.
Thx !
GpsService.java :
public class GpsService extends IntentService implements LocationListener {
private final static String TAG = "com.example.smartoo.gpsservice";
public GpsService () {
super(TAG);
Log.e("TAG", "GPS service k");
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
Intent i = new Intent("android.location.PROVIDERS_CHANGED");
i.putExtra("enabled", 1);
sendBroadcast(i);
}
}
#Override
public void onProviderDisabled(String provider) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
Intent i = new Intent("android.location.PROVIDERS_CHANGED");
i.putExtra("disnabled", 1);
sendBroadcast(i);
}
}
#Override
protected void onHandleIntent(Intent intent) {
}
}
HomeActivity.java
public class HomeActivity extends ActionBarActivity implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
//My attrs
private GoogleMap mMap = null;
Location currentLocation;
/*
* Initialize the Activity
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
//Get the map from xml file
mMap = getMap();
Intent i = new Intent(HomeActivity.this, GpsService.class);
startService(i);
}
/*
* Called when the Activity is restarted, even before it becomes visible.
*/
#Override
public void onStart() {
super.onStart();
final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//Check if GPS is enable on device.
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
showGPSDisabledAlertToUser();
}
}
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
int extra = intent.getIntExtra("enabled", -1);
//If GPS not enabled
if(extra == -1) {
extra = intent.getIntExtra("disabled", -1);
//If GPS not disabled
if (extra == -1) {
//Nothing
}
//If GPS disabled
else {
//Do something
}
}
//If GPS enabled
else {
Toast.makeText(HomeActivity.this, "GPS enabled", Toast.LENGTH_LONG).show();
currentLocation = getLocation();
setUpMapIfNeeded();
}
Toast.makeText(HomeActivity.this, "in onREceive", Toast.LENGTH_LONG).show();
}
}
}
}
For an example, first add the following permission to your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then, a simple Activity:
public class MainActivity extends Activity
{
private GpsStatusReceiver receiver = new GpsStatusReceiver();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume()
{
super.onResume();
registerReceiver(receiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}
private class GpsStatusReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
onGpsStatusChanged(isEnabled);
}
}
private void onGpsStatusChanged(boolean isEnabled)
{
// Do/start your work here.
Toast.makeText(this, "GPS enabled - " + isEnabled, 0).show();
}
}
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.