Ich arbeite an einer Anwendung und muss GPS-Standort integrieren. Ich möchte das GPS programmatisch einschalten. Die Bedingung lautet: Ich möchte den Benutzer nicht zum Einstellungsfenster senden, um ihn zu aktivieren. Ich möchte es gewaltsam aktivieren oder eine einzelne Eingabeaufforderung wird funktionieren (ähnlich der Ola Cabs Android App). Viele Fragen sind für diese Seite auf dieser Seite, aber jeder sucht nach ähnlichen Funktionen wie Ola Cabs App. Also habe ich diesen Thread gestartet, damit es für uns alle klar sein kann.Schalten Sie GPS programmgesteuert wie Ola Cabs Android App
Antwort
Hier habe ich Benutzer diesen Code
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
Berechtigungen in Ihrer Manifest-Datei:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Hallo, Danke für Ihre schnelle Antwort, aber es funktioniert nicht. Ich finde das von unten Link zuvor, http://StackOverflow.com/Questions/4721449/How-Cani-Ineable-ODER-disable-the-GPS-Programmatic-on-android – Alpesh
Es funktioniert gut für mich, wie ich habe in meinem System versucht. Ich habe eine andere Antwort gepostet, probiere diesen Link, hoffe, es funktioniert gut für dich. :) –
Sein Absturz, versuchte in drei vier Telefone – Alpesh
den Code überprüfen. Zuerst wird geprüft, ob der Standort aktiviert ist oder nicht, und der Benutzer wird aufgefordert, den Standort zu aktivieren.
private GoogleApiClient googleApiClient;
final static int REQUEST_LOCATION = 199;
// check whether gps is enabled
public boolean noLocation() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// buildAlertMessageNoGps();
enableLoc();
return true;
}
return false;
}
private void enableLoc() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Timber.v("Location error " + connectionResult.getErrorCode());
}
}).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
(Activity) context, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_LOCATION:
switch (resultCode) {
case Activity.RESULT_CANCELED: {
// The user was asked to change settings, but chose not to
finish();
break;
}
default: {
break;
}
}
break;
}
}
}
Antworten mit Code, der ist Ihr eigener Code und es ist nicht Tutorial, sollte auf StackOverflow mit Code-Formatierung zur Verfügung gestellt werden. –
Danke für den Vorschlag, wird es wieder veröffentlichen –
Danke, Mann !!! Klappt wunderbar! – GrafOrlov
Ola Cabs verwendet die neu veröffentlichte Einstellungs-API, um diese Funktionalität zu erreichen. Gemäß der neuen API muss der Benutzer nicht zur Einstellungsseite navigieren, um Standortdienste zu aktivieren, die eine nahtlose Integration für denselben ermöglichen. Bitte lesen Sie unten für weitere Informationen:
https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi
jetzt veraltet. –
Hier ist mein 100% Arbeits Code erster dependencie hinzufügen compile 'com.google.android.gms:play-services:9.2.1'
zu Ihrem build.gradle (Modul: app)
Danach erstellen Klasse mit dem Namen StartLocationAlert.java
und kopieren Sie diesen Code und fügen Sie ihn in dieser Datei
import android.app.Activity;
import android.content.IntentSender;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.example.googlemappromt.MainActivity;
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.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.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
/**
* Created by Anirudh on 20/07/16.
*/
public class StartLocationAlert implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Activity context;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
GoogleApiClient googleApiClient;
public StartLocationAlert(Activity context) {
this.context = context;
googleApiClient = getInstance();
if(googleApiClient != null){
//googleApiClient.connect();
settingsrequest();
googleApiClient.connect();
}
}
public GoogleApiClient getInstance(){
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
return mGoogleApiClient;
}
public void settingsrequest()
{
Log.e("settingsrequest","Comes");
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
// Log.e("Application","Button Clicked");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
// Log.e("Application","Button Clicked1");
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
Log.e("Applicationsett",e.toString());
}
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.
//Log.e("Application","Button Clicked2");
Toast.makeText(context, "Location is Enabled", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
@Override
public void onConnected(@Nullable Bundle bundle) {
/* MainActivity mm = new MainActivity();
mm.requestLocationUpdates();*/
Toast.makeText(context , "Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
Benutzung der obigen Klasse ist unten gezeigt
@Override
protected void onResume() {
super.onResume();
Activity mContext = MainActivity.this //change this your activity name
StartLocationAlert startLocationAlert = new StartLocationAlert(mContext);
requestLocationUpdates();
}
Und vergessen Sie nicht unter Berechtigungen in AndroidManifest.xml
Datei hinzufügen oder sonst könnte dies funktioniert nicht richtig,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Hope this könnte Ihnen helfen ..
requestLocationUpdates(); ?????? –
Es ist zu aktualisieren Standort nach dem Einschalten GPS Ich habe gerade die Verwendung von Sie wollen ganzes Projekt hinzufügen Kommentar mit Ihrer E-Mail-ID Ich werde es Ihnen weiterleiten Ich habe diese Funktion Körper Ursache, obwohl es nicht notwendig ist –
@AnirudhR. Huilgol. Könnten Sie bitte teilen Beispielcode .... Vielen Dank im Voraus –
ich eine Bibliothek erstellt haben, basierend auf Anirudh Antwort.
Kurzanleitung wie man es benutzt:
hinzufügen es Ihnen
build.gradle
Datei:compile 'net.alexandroid.utils:gps:1.6'
Implementieren
GpsStatusDetectorCallBack
Schnittstelle.Implementieren Schnittstellenmethoden:
onGpsSettingStatus
undonGpsAlertCanceledByUser
erstellen Instanzvariable:
private GpsStatusDetector mGpsStatusDetector;
Instanziieren es in
onCreate()
:mGpsStatusDetector = new GpsStatusDetector(this);
Anstelle müssen Sie den Status überprüfen und ein Dialog, wenn Bedarf hinzufügen:
mGpsStatusDetector.checkLocationSettingStatus();
Aufschalten onActivityResult und fügen Sie dort:
mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);
Weitere Informationen über die Bibliothek: https://github.com/Pulimet/GpsDetector-Library
Beispiel:
public class MainActivity extends AppCompatActivity implements GpsStatusDetector.GpsStatusDetectorCallBack {
private GpsStatusDetector mGpsStatusDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGpsStatusDetector = new GpsStatusDetector(this);
mGpsStatusDetector.checkLocationSettingStatus();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);
}
@Override
public void onGpsSettingStatus(boolean enabled) {
Log.d("TAG", "onGpsSettingStatus: " + enabled);
}
@Override
public void onGpsAlertCanceledByUser() {
Log.d("TAG", "onGpsAlertCanceledByUser");
}
}
genial bro, ich wusste nicht, wie man die Bibliothek mit mein Code bitte lass es mich wissen, wie es geht, wenn Sie etwas Freizeit zu verbringen finden –
Hallo, folgen Sie einfach der Anleitung. – Alexey
package com.example.user.myGPS;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.IntentSender;
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.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.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
public class MainActivity extends AppCompatActivity {
private GoogleApiClient googleApiClient;
final int REQUEST_CHECK_SETTINGS = 0x1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-------Code to turn on GPS------------------
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
builder.setNeedBle(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final com.google.android.gms.common.api.Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try
{
status.startResolutionForResult(MainActivity.this,REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
}
}
Vergessen Sie nicht,
Da SettingsApi veraltet und nach here in den Entwickler-Website zu überprüfen. Ich konnte das gleiche Ergebnis erzielen wie die Ola App.
das unten stehende Methode in Ihrer Aktivitätsklasse hinzufügen
private void switchOnGPS() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));
Task<LocationSettingsResponse> task = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
@Override
public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
} catch (ApiException e) {
switch (e.getStatusCode())
{
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED :
ResolvableApiException resolvableApiException = (ResolvableApiException) e;
try {
resolvableApiException.startResolutionForResult(MainActivity.this,REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//open setting and switch on GPS manually
break;
}
}
}
});
//Give permission to access GPS
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 11);
}
Rufen Sie das obige Verfahren in der Ihre Aktivität onResume Methode wie unten
@Override
protected void onResume() {
super.onResume();
switchOnGPS();
}
Manifest-Datei hinzufügen Erlaubnis jeweiligen Ort in.
, wenn es keine solche Art und Weise unter Verwendung von offiziellen SDK ist, dann pleasdy Versuchen Sie nicht, das System – pskink
Einzel prompt zu betrügen: http://stackoverflow.com/questions/31235564/locationsettingsrequest-dialog-onactivityresult-skipped/31816683#31816683 –