2

Whenever i try to turn on and turn off GPS automatically KITKAT fires java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE exception...

from the following answer from stack overflow,, Android device GPS on/off programatically
i came to know,

* For The security purpose Google developer has block above both methods which were previously working fine.

* Hence conclusion is that You can not programmatically start GPS On or Off. 

 This is the code part where exception is thrown,



/** Method for stop GPS **/
    public synchronized void onPauseGPSListener() {
        mLogger.log("Remove GPS Location Update");


 //this Line throws the exception--------------------------------


Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
            intent.putExtra("enabled", false);
            sendBroadcast(intent);
            if (locationclient != null && mlocListener != null) {
                locationclient.removeLocationUpdates(mlocListener);
                locationclient.disconnect();
                locationclient=null;
                mlocListener = null;
            }
            StoptimerForGPSRemoveListener();
            if (mcalMgr.mServerReset == 0) {
                timerForGPSStartListener();
            }
        }

        /** Method for Start GPS **/
        public synchronized void onStartGPSListener() {
            mLogger.log("Start GPS Location Update");
            if (mlocListener == null) {
                mlocListener = new MyLocationListener();
            }
            Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
            intent.putExtra("enabled", true);
            sendBroadcast(intent);
            StoptimerForGPSStartListener();
            if (mcalMgr.mServerReset == 0) {
                initGPSModule(mnFrequency, mfChangeDistance);
            } else {
                mlocListener = null;
                Intent mintent = new Intent("android.location.GPS_ENABLED_CHANGE");
                mintent.putExtra("enabled", false);
                sendBroadcast(mintent);
            }
    }

this is Logcat stack trace,

11-20 11:19:26.317: E/AndroidRuntime(7773): Process: com.teclever.tracking, PID: 7773
11-20 11:19:26.317: E/AndroidRuntime(7773): java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE from pid=7773, uid=10160
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.os.Parcel.readException(Parcel.java:1465)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.os.Parcel.readException(Parcel.java:1419)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:2451)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.app.ContextImpl.sendBroadcast(ContextImpl.java:1264)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:365)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at com.teclever.tracking.LocationGetter.onPauseGPSListener(LocationGetter.java:601)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at com.teclever.tracking.LocationGetter$1.run(LocationGetter.java:706)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.os.Handler.handleCallback(Handler.java:808)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.os.Handler.dispatchMessage(Handler.java:103)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.os.Looper.loop(Looper.java:193)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at android.app.ActivityThread.main(ActivityThread.java:5312)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at java.lang.reflect.Method.invokeNative(Native Method)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at java.lang.reflect.Method.invoke(Method.java:515)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
11-20 11:19:26.317: E/AndroidRuntime(7773):     at dalvik.system.NativeStart.main(Native Method)
11-20 11:19:27.026: E/(706): Could not open '/data/data/hotplug/cmd'
11-20 11:19:27.027: E/(706): error : 2, No such file or directory
11-20 11:19:27.104: E/(1015): appName=com.jrdcom.launcher, acAppName=/system/bin/surfaceflinger
11-20 11:19:27.104: E/(1015): 0
11-20 11:19:27.179: E/(706): Could not open '/data/data/hotplug/cmd'
11-20 11:19:27.180: E/(706): error : 2, No such file or directory
11-20 11:19:27.967: E/TelephonyProvider(833): iTelephony is null!!!

But my question is when ever i open Google maps , it turns GPS on and off without any prompt from user,,, thing is it only asks for first time when we login to our application, from that onwards it automatically turns on and off the GPS ,, how can i implement the same procedure implemented in google maps , better provide me with code examples thank you

Community
  • 1
  • 1
user39996
  • 117
  • 1
  • 10
  • No this isn't the case google map does cache location and usually shows last know location when GPS is not on/enable! – Muhammad Babar Nov 25 '14 at 12:51
  • "when ever i open Google maps , it turns GPS on and off without any prompt from user" -- not on my Nexus 4. If GPS is disabled, it pops up a dialog and forces you to go to Settings to enable GPS. Also, please bear in mind that "off and on" is not the same as "enabled and disabled". An app cannot enable or disable GPS. – CommonsWare Nov 25 '14 at 12:53
  • but whenever i open google maps notification bar shows GPS icon and disappears... may be can u know the procedure or code used in maps??? –  Nov 25 '14 at 12:54
  • @CommonsWare is that possible to enable GPS specific for an application only once for first time by asking user with alert and then automatically getting location updates – user39996 Nov 25 '14 at 12:56
  • 1
    No. If the user disables GPS, no apps can use GPS, unless the user goes back into Settings and re-enables it. – CommonsWare Nov 25 '14 at 12:59
  • @CommonsWare I'm using Moto G , i have enabled GPS and my google maps using GPS everytime without any prompt , i have installed one more app(my own app) , in my app i'm using a service to turn on and off GPS periodically , so when service has been called to it fires exception , can u suggest me the exact cause of the force close and what to do – user39996 Nov 25 '14 at 13:05
  • 2
    "i have enabled GPS and my google maps using GPS everytime without any prompt" -- correct. If you *disable* GPS, Google Maps will prompt you to enable it, if you do something in Google Maps that requires GPS (e.g., ask for it to highlight your location). " can u suggest me the exact cause of the force close and what to do" -- http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Nov 25 '14 at 13:07
  • @CommonsWare I have updated my question can u plz check , favour me some help and it will thankful – user39996 Nov 25 '14 at 13:16
  • That is a protected broadcast that can only be sent by the system. – CommonsWare Nov 25 '14 at 13:36
  • @CommonsWare do you know (or) having google documentation Link that from 4.4 GPS feature have been under control ... if know plz comment ... – user39996 Nov 26 '14 at 04:26

1 Answers1

0

Its Working Similar to google maps?

Add Dependency in build.gradle file

compile 'com.google.android.gms:play-services:8.3.0'

this or that

compile 'com.google.android.gms:play-services-location:10.0.1' enter image description here

package com.keshav.volleypostexample;

import android.content.Context;
import android.content.IntentSender;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

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.LocationSettingsStatusCodes;

import java.util.List;

public class LocationOnOff_Similar_To_Google_Maps 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) LocationOnOff_Similar_To_Google_Maps.this.getSystemService(Context.LOCATION_SERVICE);
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) {
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
            finish();
        }
        // Todo Location Already on  ... end

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

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) {
            Log.e("keshav","Gps already enabled");
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not enabled",Toast.LENGTH_SHORT).show();
            enableLoc();
        }else{
            Log.e("keshav","Gps already enabled");
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.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(LocationOnOff_Similar_To_Google_Maps.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(LocationOnOff_Similar_To_Google_Maps.this, REQUEST_LOCATION);

                                finish();
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }
    }

}
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53