像 Ola Cabs Android 应用程序一样以编程方式打开 GPS

Posted

技术标签:

【中文标题】像 Ola Cabs Android 应用程序一样以编程方式打开 GPS【英文标题】:Turn GPS on programmatically like Ola Cabs Android app 【发布时间】:2015-12-08 17:28:07 【问题描述】:

我正在开发一个应用程序,需要集成 GPS 定位。我想以编程方式打开 GPS。条件是:我不想将用户发送到设置面板来启用它。我想强制启用它,否则单个提示将起作用(类似于 Ola Cabs android 应用程序)。这个网站上有很多问题,但每个人都在寻找类似的功能,比如 Ola Cabs 应用程序。所以我开始了这个线程,以便我们所有人都清楚。

【问题讨论】:

如果官方SDK没有这种方式,请不要试图欺骗系统 单提示:***.com/questions/31235564/… 【参考方案1】:

这是我的 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"/>

希望这对你有帮助..

【讨论】:

它是在打开 gps 后开始更新位置我刚刚使用了你想要整个项目的用法添加评论与你的电子邮件 ID 我会转发给你我努力把那个功能体的原因没必要 @AnirudhR.Huilgol。你能分享示例代码吗....提前非常感谢 @ParmendraSingh 抱歉错误的 URL github.com/huilgolAni19/SampleGpsApp 这是实际的 URL 我们可以在其中获取当前位置(经度、纬度)吗? @WealInfotech 是的,您可以转到此链接 github.com/huilgolAni19/SampleGpsApp 您将找到示例应用程序,其中我展示了如何获取当前纬度经度【参考方案2】:

检查下面的代码。首先,它会检查位置是否启用,并提示用户启用位置。

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;
        

    


【讨论】:

应在 *** 上提供带有代码格式的答案,这是您自己的代码,而不是教程。 感谢您的建议,将重新发布它【参考方案3】:

由于 SettingsApi 已被弃用,并且在查看开发人员网站 here 之后。我能够获得与 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);

在 Activity 的 onResume 方法中调用上述方法,如下所示

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

在 Manifest 文件中添加相应的位置权限。

【讨论】:

【参考方案4】:

我创建了一个基于 Anirudh 答案的库。

如何使用它的简短指南:

    添加给你build.gradle文件:

    compile 'net.alexandroid.utils:gps:1.6'

    实现GpsStatusDetectorCallBack接口。

    实现接口方法onGpsSettingStatusonGpsAlertCanceledByUser

    创建实例变量:

    private GpsStatusDetector mGpsStatusDetector;
    

    实例化它在onCreate():

     mGpsStatusDetector = new GpsStatusDetector(this);
    

    您需要检查状态并在需要时显示对话框添加

    mGpsStatusDetector.checkGpsStatus();
    

    覆盖 onActivityResult 并添加:

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

【讨论】:

太棒了兄弟,我不知道如何用我的代码制作图书馆,如果你有闲暇时间,请告诉我如何做 您好,请按照指南进行操作。 无法在 java 文件中找到 checkLocationSettingStatus() 方法 请使用 checkGpsStatus() 方法。 (答案已更新)【参考方案5】:

这里我有用户这个代码

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"/>

【讨论】:

您好,感谢您的快速回复,但它不起作用。我之前从下面的链接中找到了这个,***.com/questions/4721449/… 它对我来说很好,因为我在我的系统中尝试过。我已经发布了另一个答案,试试这个链接,希望它对你有用。 :)【参考方案6】:

Ola Cabs 正在使用新发布的设置 API 来实现此功能。根据新 API,用户无需导航到设置页面即可启用位置服务,从而实现无缝集成。详情请阅读以下内容:

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

【讨论】:

【参考方案7】:
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;
                    
                
            );

        


    



【讨论】:

不要忘记在 android manifest 中添加

以上是关于像 Ola Cabs Android 应用程序一样以编程方式打开 GPS的主要内容,如果未能解决你的问题,请参考以下文章

Laravel Websocket 向特定的 Android 设备发送消息

android:如何像 android market 一样让标签页翻转?

android - 像 uber 应用一样的底页

android:如何像 Photoshop 一样创建叠加混合?

Android : 像 Facebook 一样有多个图像和视频的新闻源

是否可以像在 android 中一样为我的应用程序的活动创建一个最近的屏幕