B
B
bart12k2019-07-26 08:35:57
android studio
bart12k, 2019-07-26 08:35:57

How to correctly request permissions in the service?

There is a code for determining coordinates over the network:

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //  Toast toast = Toast.makeText(this, "Permission failed", Toast.LENGTH_SHORT);
            //   toast.show();
            return;
        } else {

            //   Toast toast = Toast.makeText(this, "is work", Toast.LENGTH_SHORT);
            //    toast.show();
        }

        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);


// GPS_PROVIDER отправить GPS
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new MyListener());

If it's in the activity, everything is fine, everything works. But as soon as it is transferred to the MyService service, it starts to swear when permission is requested ... Maybe I'm doing something wrong?
It breaks like this:
Process: com.example.gps, PID: 10673
    java.lang.RuntimeException: Unable to instantiate service com.example.gps.MyService: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3925)
        at android.app.ActivityThread.access$1500(ActivityThread.java:220)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1868)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7319)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
        at android.content.ContextWrapper.getSystemService(ContextWrapper.java:752)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2019-07-26
@402d

There is no context.
Getcontext().getservice
But I personally don't like it when I have something hanging in the background with geolocation on my phone.
I demolish such conditionally necessary or nail services with handles

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question