web-dev-qa-db-ja.com

OlaCabsのようにプログラムでGPSをオンにするAndroid app

私はアプリケーションに取り組んでおり、GPS位置情報を統合する必要があります。プログラムでGPSをオンにしたい。条件は次のとおりです。ユーザーを設定パネルに送信して有効にしたくない。強制的に有効にしたい、または単一のプロンプトが機能する(Ola Cabs Android app)と同様)。このサイトではこれについて多くの質問がありますが、誰もが次のような同様の機能を探しています。 Ola Cabsアプリ。それで、私たち全員が明確にできるように、このスレッドを開始しました。

8
Alpesh

これが私の100%動作するコードです。最初にこの依存関係compile 'com.google.Android.gms:play-services:9.2.1'をbuild.gradle(Module:app)に追加します。

その後、StartLocationAlert.Javaという名前のクラスを作成し、このコードをコピーしてこのファイルに貼り付けます

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) {

    }
}

上記のクラスの使用法を以下に示します

 @Override
    protected void onResume() {
        super.onResume();
        Activity mContext = MainActivity.this //change this your activity name 
        StartLocationAlert startLocationAlert = new StartLocationAlert(mContext);

       requestLocationUpdates();

    }

また、AndroidManifest.xmlファイルに以下の権限を追加することを忘れないでください。そうしないと、これが正しく機能しない可能性があります

 <uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION"/>

これがお役に立てば幸いです。

10

以下のコードを確認してください。まず、場所が有効になっているかどうかを確認し、ユーザーに場所を有効にするように求めます。

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;
        }

    }

}
7
Ashish Lingayat

SettingsApiは非推奨であるため、開発者サイトにチェックインした後 ここ 。 Olaアプリと同じ結果を出すことができました。

以下のメソッドをActivityクラスに追加します

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);
}

以下のように、アクティビティのonResumeメソッドで上記のメソッドを呼び出します

@Override
protected void onResume() {
    super.onResume();
    switchOnGPS();
}

マニフェストファイルにそれぞれのロケーション権限を追加します。

1
Harish Rn

アニルーダの答えに基づいてライブラリを作成しました。

それを使用する方法の短いガイド:

  1. それをあなたに追加_build.gradle_ファイル:

    _compile 'net.alexandroid.utils:gps:1.6'_

  2. ImplementGpsStatusDetectorCallBackインターフェース。

  3. インターフェースメソッドの実装onGpsSettingStatusおよびonGpsAlertCanceledByUser

  4. Createインスタンス変数:

    _private GpsStatusDetector mGpsStatusDetector;
    _
  5. Instantiateit in onCreate()

    _ mGpsStatusDetector = new GpsStatusDetector(this);
    _
  6. 代わりに、ステータスを確認し、必要に応じてダイアログを表示する必要がありますadd

    _mGpsStatusDetector.checkGpsStatus();
    _
  7. OverrideonActivityResultそしてそこに追加します:

    _mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode);
    _

ライブラリの詳細: https://github.com/Pulimet/GpsDetector-Library


例:

_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");
    }
}
_
1
Alexey

ここに私はユーザーにこのコードを持っています

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);
    }
    }

マニフェストファイルの権限:

<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"/>
0
Parth Bhayani

Ola Cabsは、この機能を実現するために、新しくリリースされた設定APIを使用しています。新しいAPIに従って、ユーザーは設定ページに移動して位置情報サービスを有効にする必要がなく、位置情報サービスをシームレスに統合できます。詳細については、以下をお読みください。

https://developers.google.com/Android/reference/com/google/Android/gms/location/SettingsApi

0
Abhi
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;
                    }
                }
            });

        }


    }


}
0
blazkowicz