androidandroid-gps

OnNmeaMessageListener not working for samsung j7, android 6.0.1


When testing an app that uses the OnNmeaMessageListener on a Samsung J7 the app breaks with this error

enter image description here

And I really don't get what is the problem, I've tested on other devices and the app works.

Code that I'm testing:

 LM.addNmeaListener(new OnNmeaMessageListener() {
                @Override
                public void onNmeaMessage(String nmea, long timestamp) {
                 // do stuff
                } 
    });

Solution

  • Ok I found a possible solution for SDK versions below 24

    if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
        GpsStatus.NmeaListener nmeaListenerDeprecated = new GpsStatus.NmeaListener() {
            @Override
            public void onNmeaReceived(long timestamp, String nmea) {
                processNmeaData(nmea, timestamp);
            }
        };
        try {
            //noinspection JavaReflectionMemberAccess
            Method addNmeaListener =
                    LocationManager.class.getMethod("addNmeaListener", GpsStatus.NmeaListener.class);
            addNmeaListener.invoke(LM, nmeaListenerDeprecated);
        } catch (Exception exception) {
            // TODO
        }
    } else {
        LM.addNmeaListener(new OnNmeaMessageListener() {
            @Override
            public void onNmeaMessage(String nmea, long timestamp) {
                processNmeaData(nmea, timestamp);
            }
        });
    }
    

    with that solution I manged to get NMEA working for new and older devices.