Android programmatically enable gps

Android Turn on GPS programmatically

Jan 2, 2019 · 3 min read

In our previous article, we have taught you how to get location using FusedLocationProviderClient and we also mentioned in that article that for using this feature, you need to turn on device GPS manually by redirecting to settings of your device.

Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.

First method:
By usin g this, the user will be redirected to the Settings page of your device and user has to turn on GPS manually.

Second method:
In this method, we will show you code to turn on GPS using android gms location request and setting clients. Here we provide a custom class GpsUtils.java with a code written in it with method turnGPSOn(). The method has a callback listener to check the current status of GPS. If GPS is already turned on, no further code will be determined and callback revert true as GPS is on. Let’s look at the code below and we will show how to use GpsUtils.java.

SettingsClient class is the main key point for interacting with location-based API. This API makes it easy for an app to ensure that the device’s system settings are properly configured for the app’s location needs.

LocationSettingsRequest Specifies the types of location services the client is interested in using. Settings will be checked for optimal functionality of all requested services. Use LocationSettingsRequest.Builder to construct this object.

GPS Dialog will be shown for SettingsClient’s failure callback and it will result in an activity’s onActivityResult(). So basically if the user agrees for turn on GPS, we can enable GPS flag in our activity.

and now call GpsUtils class before getting a location.

We recommend you to put this code in onCreate() of your activity. So that, turn on GPS and getting a location works well one by one. And also GPS takes some minor delay to trace your device location.

We have provided code in the previous article to get a location. Thus, we made changes for GPS in that code and republish the same code.

Читайте также:  Hs tutor rus android

Find code here. Code contains previous article example for getting the current location.

Источник

Android programmatically enable gps

Turn on GPS automatically? What is that? Or we have seen it in different apps like Uber, Ola etc. but how to implement that?

We have seen various mobile applications want us GPS to turn on. And we proceed. First we select YES from dialog asking ‘You need to turn on GPS to continue’ or something like that (typical traditional alert dialog). Then it moves to the common GPS screen, showing list of other apps accessing GPS. However, next we toggle the location switch. And finally the back button. It returns to the application and wait for the location to be fetched and blah blah blah…

Tired enough! right?

Though it takes a few seconds(typically 4-5 seconds), still it feels like a huge task we are doing and of course, we don’t like it (at least some of us). It diverts our view from the app for a little but significant slice of time.

So we want to be a little bit lazy, right? This is where this article stands in , ‘How we can turn GPS automatically on Android’. Our goal is skip all of the steps written above and only one tap to switch on the GPS automatically.

ICE BREAK

We are assuming, you are accustomed with creating and running android applications. (If not, you can read this well written article). So let’s concentrate in main stream of discussion.

We will use Google Play Location Service to achieve our goal.

Источник

Programmatically Enable Android GPS and Location Services

I remember the “good ol’ days” of location-based programming where there was a simple API call that allowed an application to enable or disable a mobile device’s GPS service. Today, user privacy and security concerns make that sort’a thing no longer possible.

In today’s world, a phone’s user generally has ultimate control of what features are and are not enabled on their phone. Although I agree this behavior is best for users, it definitely creates headaches for developers.

The one thing we know we can’t do as developers, is display a message that simply says “Hey! Go turn on your GPS”. Seeing a message like that would cause most users to uninstall our app and look for an app that’s easier to use.

The good news is that as developers we can send the user directly to the location settings screen right from within our app with a simple Intent.

Читайте также:  Как разрешить доступ камере андроид

The exact format of the screen the user sees will vary based on their Android version and device model, but the above code will always take them to the appropriate settings screen. On my Samsung device, the ACTION_LOCATION_SOURCE_SETTINGS screen looks like the following…

In general what I’ll do is use the LocationManager class to check for the availability of the required location services. If the services aren’t enabled, I’ll show an AlertDialog informing the user of what they need to do and then show the settings screen in the dialog’s click handler. Here’s that code…

That little bit of code can go a long way to both ensuring that your app has access to the required location services and that the user has a positive experience.

Posted by hedgehogjim

30+ years as a professional software dev, 17+ years developing mobile solutions, Pluralsight Author, Founder JWHH, LLC

Источник

AndroidEasyCode

Thursday, 7 February 2019

Android GPS enable by programmatically

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener <
private TextView latitudeTextView,longitudeTextView;
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView=(TextView)findViewById(R.id.latitudeTextView);
longitudeTextView=(TextView)findViewById(R.id.longitudeTextView);
setUpGClient();
>

private synchronized void setUpGClient() <
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
>

@Override
public void onLocationChanged(Location location) <
mylocation = location;
if (mylocation != null) <
Double latitude=mylocation.getLatitude();
Double longitude=mylocation.getLongitude();
latitudeTextView.setText(«Latitude : «+latitude);
longitudeTextView.setText(«Longitude : «+longitude);
//Or Do whatever you want with your location
>
>

@Override
public void onConnected(Bundle bundle) <
checkPermissions();
>

@Override
public void onConnectionSuspended(int i) <
//Do whatever you need
//You can display a message here
>

@Override
public void onConnectionFailed(ConnectionResult connectionResult) <
//You can display a message here
>

private void getMyLocation() <
if(googleApiClient!=null) <
if (googleApiClient.isConnected()) <
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) <
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback () <

@Override
public void onResult(LocationSettingsResult result) <
final Status status = result.getStatus();
switch (status.getStatusCode()) <
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied.
// You can initialize location requests here.
int permissionLocation = ContextCompat
.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) <
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
>
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
// But could be fixed by showing the user a dialog.
try <
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Ask to turn on GPS automatically
status.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS_GPS);
> catch (IntentSender.SendIntentException e) <
// Ignore the error.
>
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied.
// However, we have no way
// to fix the
// settings so we won’t show the dialog.
// finish();
break;
>
>
>);
>
>
>
>

Читайте также:  Кастомизация button android studio

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) <
switch (requestCode) <
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) <
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
>
break;
>
>

private void checkPermissions() <
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) <
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) <
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
>
>else <
getMyLocation();
>

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) <
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) <
getMyLocation();
>
>
>

xmlns:tools=»http://schemas.android.com/tools»
android:id=»@+id/activity_main»
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical»
android:padding=»20dp»>

android:layout_width=»match_parent»
android:textColor=»#000000″
android:gravity=»center»
android:textSize=»20sp»
android:layout_height=»wrap_content»
android:text=»My Location»/>

android:layout_marginTop=»10dp»
android:textSize=»18sp»
android:id=»@+id/latitudeTextView»
android:text=»Latitude : »
android:layout_width=»match_parent»
android:layout_height=»wrap_content»/>

android:layout_marginTop=»10dp»
android:textSize=»18sp»
android:id=»@+id/longitudeTextView»
android:text=»Longitude :»
android:layout_width=»match_parent»
android:layout_height=»wrap_content»/>

Источник

How can I enable or disable the GPS programmatically on Android?

Posted by: admin November 19, 2017 Leave a comment

I know that the question about turning on/off GPS programatically on android has been discussed many times, and the answer is always the same:

“You can’t for security/privacy reasons, you have to forward to location preferences screen and let the user enable/disable it.”

I understand that, however I recently bought Tasker from the market and, among many other things that you can accomplish with it, you can set rules to auto-enable GPS on entering pre-determined applications and disable it on exit (see here for the tutorial on how to do it, and it just works!) and this app can’t be signed with the firmware signing key as it works on many android versions and different devices and you don’t even need to be rooted.

I would like to do this in my app. Of course, I don’t want to blow up the users privacy, so I would first ask the user if he wants to turn it on automatically with the typical “remember my decision” checkbox and if he answers yes, enable it.

Does anybody have any idea or clue on how Tasker achieves this?

the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.

here’s some example code i use

use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.

Источник

Оцените статью