簡體   English   中英

如何在 Android 上打開 GPS

[英]How to turn on the GPS on Android

我正在開發一個需要激活 GPS 的 android 應用程序。

我在很多論壇上閱讀了很多主題,我找到的答案是:

這是不可能的

但是……“Cerberus”應用程序打開了我的 GPS……所以……這是可能的!

誰能幫我這個?

不,這是不可能的,也是不恰當的。 您不能在沒有用戶權限的情況下管理用戶的電話。 用戶必須進行交互才能啟用 GPS。

從 Play 商店:

“當您嘗試本地化您的設備時,如果 GPS 處於關閉狀態,Cerberus 會自動啟用 GPS (僅適用於 Android < 2.3.3) ,您可以保護它免遭未經授權的卸載——更多信息請參閱應用程序配置。”

你可以這樣做:

startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

我認為我們有更多更好的版本來啟用位置,而無需像谷歌地圖一樣打開設置。

它看起來像這樣 -

在此處輸入圖片說明

在 gradle 中添加依賴項 -編譯 'com.google.android.gms:play-services-location:10.0.1'

public class MapActivity extends AppCompatActivity {

    protected static final String TAG = "LocationOnOff";

 
    private GoogleApiClient googleApiClient;
    final static int REQUEST_LOCATION = 199;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setFinishOnTouchOutside(true);

        // Todo Location Already on  ... start
        final LocationManager manager = (LocationManager) MapActivity.this.getSystemService(Context.LOCATION_SERVICE);
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapActivity.this)) {
            Toast.makeText(MapActivity.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
        }
        // Todo Location Already on  ... end

        if(!hasGPSDevice(MapActivity.this)){
            Toast.makeText(MapActivity.this,"Gps not Supported",Toast.LENGTH_SHORT).show();
        }

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapActivity.this)) {
            Log.e("TAG","Gps already enabled");
            Toast.makeText(MapActivity.this,"Gps not enabled",Toast.LENGTH_SHORT).show();
            enableLoc();
        }else{
            Log.e("TAG","Gps already enabled");
            Toast.makeText(MapActivity.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
        }
    }


    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null)
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    private void enableLoc() {

        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(MapActivity.this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {

                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            googleApiClient.connect();
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {

                            Log.d("Location error","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(MapActivity.this, REQUEST_LOCATION);
                       } catch (IntentSender.SendIntentException e) {
                           // Ignore the error.
                       }
                       break;
                 }
             }
         });
     }

}

曾經有一個漏洞允許沒有特殊權限的應用程序打開 GPS。 從 2.3(在大多數 ROM 中)開始,該漏洞不再存在。 這是另一個談論它的帖子,

如何在 Android 上以編程方式啟用或禁用 GPS?

“啟用 GPS”是一項安全設置,因此您必須具有 WRITE_SECURE_SETTINGS 權限。 但是,這是受簽名保護的權限,因此除非使用制造商的平台證書簽名,否則您的應用程序不會被授予此權限。

正確的做法是將用戶發送到位置設置頁面,並讓他們根據需要啟用 GPS。 例如,

Intent i = new
Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.gps_disabled_message)
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);                  
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

這會創建一個警報並允許用戶轉到設置屏幕並點擊后退按鈕立即返回到您的應用程序。 據我所知,power widget 漏洞在 2.3 之后不起作用。

使用此代碼 //turnGPSON 調用后 setcontentView(xml)

 private void turnGPSOn() {

    String provider = android.provider.Settings.Secure.getString(
            getContentResolver(),
            android.provider.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);
    }
}**

你可能想看看這個線程

如何在 Android 上以編程方式啟用或禁用 GPS?

這是從該線程復制的代碼

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


   }
}

但不推薦該解決方案,因為它不適用於 android 版本 > 2.3 假設......請檢查評論

GoogleApiClient已被棄用,我們需要使用SettingsClient和 GoogleApi 來啟用 GPS,而無需像 Google Maps、OLA、Zomato 等那樣進入位置設置。以下代碼支持從 4.4 或更低到 11+ 的任何 Android 版本

gradle 文件中所需的依賴項:

implementation 'com.google.android.gms:play-services-location:17.1.0'

要檢查 GPS 狀態 ON 或 OFF:

private static LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
public static boolean isGpsEnabled(){
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

如果 GPS 已經啟用,那么我們將顯示吐司通知,否則將要求打開 GPS。

//Defining constant request code, add in your activity class
private static final int REQUEST_CHECK_SETTINGS = 111;

if(!isGpsEnabled()){
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

        builder.setAlwaysShow(true); //this displays dialog box like Google Maps with two buttons - OK and NO,THANKS

        Task<LocationSettingsResponse> task =
                LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());

        task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
            @Override
            public void onComplete(Task<LocationSettingsResponse> task) {
                try {
                    LocationSettingsResponse response = task.getResult(ApiException.class);
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                } catch (ApiException exception) {
                    switch (exception.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the
                            // user a dialog.
                            try {
                                // Cast to a resolvable exception.
                                ResolvableApiException resolvable = (ResolvableApiException) exception;
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                resolvable.startResolutionForResult(
                                        YOUR_ACTIVITY.this,
                                        REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            } catch (ClassCastException e) {
                                // Ignore, should be an impossible 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.
                            break;
                    }
                }
            }
        });
    } else {
        Toast.makeText(getApplicationContext(), "GPS is already Enabled!", Toast.LENGTH_SHORT).show();
    }
}

如果 GPS 未開啟,則流程將轉到 RESOLUTION_REQUIRED 並調用 startResolutionForResult ,它將由 onActivityResult 處理

現在,添加 onActivityResult 方法 -

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);

        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        Toast.makeText(getApplicationContext(),"User has clicked on OK - So GPS is on", Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(getApplicationContext(),"User has clicked on NO, THANKS - So GPS is still off.", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

如果 resultCode 是 RESULT_OK,這意味着用戶允許為 RESULT_CANCELED 打開其他 GPS,您可以再次詢問或顯示基本原理對話框。

  • 您可以將上面的代碼包裝在方法中並在您需要的任何地方調用
  • 在構建 LocationRequest 時,您可以根據應用程序的要求設置 Interval、Priority、SmallestDisplacement、FatestInterval 等。
  • 我們使用了 Task api 而不是 PendingResult

對於官方文檔,請參閱 - https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM