tahan yaf
tahan yaf

Reputation: 1

getLastKnownLocation is null when Myapp is Running in background in android 12

I wrote a program that when called I get contact information and location information of the person with api I used "BroadcastReceiver" for this. My problem is that when the program is open, it gives me the correct location and everything works fine, but when the program is running in the background, it shows the location as null. When I go to the program and open the program, everything is correct again

help me!

If my method is wrong, please tell me the right way

This is my problem on Android 12 and it is correct on lower Android



if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {

    Toast.makeText(context, "RINGING", Toast.LENGTH_SHORT).show();

LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(context.LOCATION_SERVICE);

locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
Lat = String.valueOf(location.getLatitude());
Lng = String.valueOf(location.getLongitude());

        }
       
    }

};

if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    return;

} else {

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, locationListener);

}

Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {

    Latitude = location.getLatitude();
    Longitude = location.getLongitude();

}

}

Upvotes: 0

Views: 296

Answers (0)

Related Questions