Search code examples
javaandroidgeolocationlocationandroid-manifest

java.lang.ClassCastException while Adding Permission in Service class to Fetch Location


I am trying to build a simple location provider with a service that should update location in time, so i did this service:

public class MyService extends Service
{
    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;

    private final IBinder mBinder = new LocalBinder();
    private Intent intent;

    Location mLastLocation;

    public class LocalBinder extends Binder {
        public MyService getServerInstance() {
            return MyService.this;
        }
    }

    public Location getLocation(){
        return mLastLocation;
    }


    private class LocationListener implements android.location.LocationListener
    {

        public LocationListener(String provider)
        {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location)
        {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
            Log.d("HELLO",String.valueOf(mLastLocation.getLatitude()));
        }


        @Override
        public void onProviderDisabled(String provider)
        {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    LocationListener[] mLocationListeners = new LocationListener[] {
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };


    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate()
    {
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy()
    {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions((Activity) getApplicationContext(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                        30);
            }
        }
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
}

the last part where i check the permission for Coarse location fails because the casting of the getAplicationContext() here:

 mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions((Activity) getApplicationContext(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                        30);
            }
        }
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }

when i start the service on my main activity i get this error:

06-10 15:33:37.682 28790-28790/com.example.afcosta.inesctec.pt.gpstracker E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                            Process: com.example.afcosta.inesctec.pt.gpstracker, PID: 28790
                                                                                            java.lang.RuntimeException: Unable to create service com.example.afcosta.inesctec.pt.gpstracker.MyService: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
                                                                                                at android.app.ActivityThread.handleCreateService(ActivityThread.java:3201)
                                                                                                at android.app.ActivityThread.-wrap5(ActivityThread.java)
                                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                             Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
                                                                                                at com.example.afcosta.inesctec.pt.gpstracker.MyService.initializeLocationManager(MyService.java:152)
                                                                                                at com.example.afcosta.inesctec.pt.gpstracker.MyService.onCreate(MyService.java:109)
                                                                                                at android.app.ActivityThread.handleCreateService(ActivityThread.java:3191)
                                                                                                at android.app.ActivityThread.-wrap5(ActivityThread.java) 
                                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
                                                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                                at android.os.Looper.loop(Looper.java:154) 
                                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                                                at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Any tip? 


Solution

  • Just remove the check and initialize it normally

    private void initializeLocationManager() {
            Log.e(TAG, "initializeLocationManager");
            if (mLocationManager == null) {
                mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            }
        }