1

I am using FCM and getting a notification too, in that trying to get a latitude and longitude of a person, wherever he or she gets a notification to him or her without entering an application in android but getting 0.0 in latitude and longitude.

I am not done anything in MainActivity because get a location in the background and send that to a server

Below is my MyFirebaseMessagingService code:

public class MyFirebaseMessagingService extends FirebaseMessagingService implements PowerConnectionReciever.BatteryCallback 
{

LocationTrack locationTrack;
private double longitude,latitude;
Context context=this;
IntentFilter intentfilter;
private PowerConnectionReciever powerConnectionReciever=new 
PowerConnectionReciever();
private String batterystatus;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // ...


    Log.wtf(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.wtf(TAG, "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long-running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
           // scheduleJob();

        } else {
            // Handle message within 10 seconds
           // handleNow();

        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.wtf(TAG, "Message Notification Body: " + 
         remoteMessage.getNotification().getBody());
        Log.wtf("Status","Message arrived");
        intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        locationTrack = new LocationTrack(context);

        if (locationTrack.canGetLocation()) {

            longitude = locationTrack.getLongitude();
            latitude = locationTrack.getLatitude();

            context.registerReceiver(powerConnectionReciever, intentfilter);

            Toast.makeText(this, "Locatin"+latitude+","+locationTrack, Toast.LENGTH_SHORT).show();
        } else {

            locationTrack.showSettingsAlert();
        }


    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

@Override
public void batteryInfo(boolean isCharging, boolean status, int percent) {
    Toast.makeText(getApplicationContext(), "Longitude:" + Double.toString(longitude) + "\nLatitude:" + Double.toString(latitude) + "\nBattery status:" + percent+"%", Toast.LENGTH_SHORT).show();

    batterystatus = "isCharging: " + isCharging + "\n" + "\n" +
            "isCharged:" + status + "\n" + "\n" +
            "Percent: " + percent + "\n";

    Log.wtf("BStatus", batterystatus);
    }
   }

LocationTrack Class code:

public class LocationTrack extends Service implements LocationListener {

private final Context mContext;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;

public LocationTrack(Context mContext) {
    this.mContext = mContext;
    getLocation(mContext);
}

private Location getLocation(Context mContext) {

    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // get GPS status
        checkGPS = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // get network provider status
        checkNetwork = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!checkGPS && !checkNetwork) {
            Toast.makeText(mContext, "No Service Provider is available", Toast.LENGTH_SHORT).show();
        } else {
            this.canGetLocation = true;

            // if GPS Enabled get lat/long using GPS Services
            if (checkGPS) {

                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                }
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    loc = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (loc != null) {
                        latitude = loc.getLatitude();
                        longitude = loc.getLongitude();
                    }
                }


            }


            if (checkNetwork) {

                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                }
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    loc = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }

                if (loc != null) {
                    latitude = loc.getLatitude();
                    longitude = loc.getLongitude();
                }
            }

        }


    } catch (Exception e) {
        e.printStackTrace();
    }

    return loc;
}

public double getLongitude() {
    if (loc != null) {
        longitude = loc.getLongitude();
    }
    return longitude;
}

public double getLatitude() {
    if (loc != null) {
        latitude = loc.getLatitude();
    }
        return latitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);


    alertDialog.setTitle("GPS is not Enabled!");

    alertDialog.setMessage("Do you want to turn on GPS?");


    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });


    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });


    alertDialog.show();
}


public void stopListener() {
    if (locationManager != null) {

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.removeUpdates(LocationTrack.this);
    }
}

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

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
}
Omar Einea
  • 2,478
  • 7
  • 23
  • 35

1 Answers1

0

Reason why you aren't getting lat-long when app is in background:

-->> You are Sending message from Firebase console

-->> Message contains notification payload.

-->> If app is in background, FCM notification is displayed in notification tray but onMessageReceived() is not called and it never fetches lat-long from LocationTrack.

-->> Results into 0.0

The solution is to send data only FCM message from server as you can't send data only message from Firebase Console. In that case onMessageReceived() will be called even when app is in background.

If you want to send data only payload to particular device id, send JSON like:

{ 
 "message":
     { 
      "token":"yourDeviceToken",
      "data":
          {      
           "keyFoo":"valueBar"   
          },
       "android":
          {
           "priority":"high"
           "ttl":"3600s"
          }
     }
}  
global_warming
  • 833
  • 1
  • 7
  • 11