java - 服务启动时尝试调用位置权限但应用程序崩溃

标签 java android android-service android-location foreground-service

我的应用程序中有一个按钮,可以在我的应用程序中启动服务。该服务需要获得许可才能运行。我已向服务添加了权限请求,但是当我按下按钮启动服务时,我的应用程序崩溃了。这是服务

public class MQTTService extends Service {
        private PowerManager.WakeLock wakeLock;
        private MqttAndroidClient clientPhone;
        public static String uri;
        private FusedLocationProviderClient fusedLocationClient;
        private LocationRequest locationRequest;



        public void     MQTTService() {
            clientPhone = new MqttAndroidClient(this, serverUri, clientId);
            clientPhone.setCallback(new MqttCallback() {
                public void connectComplete(boolean b, String s) {

                }
                @Override
                public void connectionLost(Throwable throwable) {

                }
                @Override
                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    Log.w("Mqtt", mqttMessage.toString());
                    Log.e("message ", String.valueOf(mqttMessage));
                    Toast.makeText(MQTTService.this, "Crash Occurred", Toast.LENGTH_SHORT).show();
                    Intent dialogIntent = new Intent(MQTTService.this, alert.class);
                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(dialogIntent);
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
        }
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }

        @Override
        public void onCreate() {
            super.onCreate();
            callPermissions();
            requestLocationUpdates();

        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }

            if(clientPhone!=null) {
            /*unregisterResources is needed,otherwise receive this error:
              has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient*/
                try {
                    clientPhone.unregisterResources();
                    clientPhone.close();
                    clientPhone.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            unregisterReceiver(m_ScreenOffReceiver);
            m_ScreenOffReceiver = null;

        }
        public void requestLocationUpdates() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
                fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

                locationRequest = new LocationRequest();
                locationRequest.setInterval(2000);
                locationRequest.setFastestInterval(4000);
                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

                fusedLocationClient.requestLocationUpdates(locationRequest, new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        super.onLocationResult(locationResult);
                        uri = "http://maps.google.com/maps?saddr=" + locationResult.getLastLocation().getLatitude() + "," + locationResult.getLastLocation().getLongitude();
                    }
                }, getMainLooper());
            }
        }
    public void callPermissions(){
        String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
        Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() {
            @Override
            public void onGranted() {
                // do your task.
                requestLocationUpdates();
            }

            @Override
            public void onDenied(Context context, ArrayList<String> deniedPermissions) {
                super.onDenied(context, deniedPermissions);
                callPermissions();
            }
        });
    }


    }

这是我的堆栈跟踪

2020-05-04 20:32:29.440 17319-17357/com.example.carcrashdetection E/Perf: Fail to get file list com.example.carcrashdetection
2020-05-04 20:32:29.440 17319-17319/com.example.carcrashdetection E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.carcrashdetection, PID: 17319
    java.lang.RuntimeException: Unable to create service com.example.carcrashdetection.MQTTService: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:4082)
        at android.app.ActivityThread.access$1800(ActivityThread.java:231)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1968)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
        at android.app.ContextImpl.startActivity(ContextImpl.java:964)
        at android.app.ContextImpl.startActivity(ContextImpl.java:940)
        at android.content.ContextWrapper.startActivity(ContextWrapper.java:383)
        at com.nabinbhandari.android.permissions.Permissions.check(Permissions.java:121)
        at com.example.carcrashdetection.MQTTService.callPermissions(MQTTService.java:282)
        at com.example.carcrashdetection.MQTTService.onCreate(MQTTService.java:95)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:4070)
        at android.app.ActivityThread.access$1800(ActivityThread.java:231) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1968) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7682) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
2020-05-04 20:32:29.440 17319-17357/com.example.carcrashdetection E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-05-04 20:32:29.444 17319-17319/com.example.carcrashdetection I/Process: Sending signal. PID: 17319 SIG: 9

我在原始服务中有更多方法,但出于这个问题的目的,我删除了它们,因为我不认为它们是问题所在。自从我添加了位置方法和访问位置的权限以来,我的应用程序开始崩溃。我调用权限是错误的吗?

最佳答案

您的问题与权限无关。您的应用程序在这里崩溃了:

2020-05-04 20:32:29.440 17319-17357/com.example.carcrashdetection E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: 尝试获取空数组的长度

关于java - 服务启动时尝试调用位置权限但应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61600182/

相关文章:

android - 我是否需要通过 IntentService 中的父类(super class) onCreate 和 onDestroy 方法调用?

java - 在并行执行模拟中找到正确的随机种子数

java - Spring Boot 更改数据源以指向 mysql 数据库

Java - 数字基数计算器(即基数 10 到基数 5)

android - 是否有行业标准让 Android 的按钮文本为大写字母或小写字母?

android - 如何实现Android广播接收器

java - 在 ScrollView 中,EditText 获得了不必要的焦点

Android TabLayout 标题本地化不起作用

android - 在 MiniControllerFragment 中调用 super.onCreateView() 时出现 NullPointerException

android - Google IO Rest 设计模式,完成 ContentProvider 并坚持从网络获取数据