我正在使用FCM并获得通知,试图获得一个人的经纬度,无论他或她在没有进入Android应用程序的情况下向他或她发送通知,但在中获得0.0纬度和经度。
我在MainActivity中没有做任何事情,因为在后台获取一个位置并将其发送到服务器
以下是我的MyFirebaseMessagingService代码:
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类代码:
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) {
}
}
答案 0 :(得分:0)
当应用处于后台时,你没有得到长时间的原因:
- >> 您正在从Firebase控制台发送消息
- >> 消息包含通知有效负载。
- >> 如果应用在后台,FCM notification is displayed in notification tray but onMessageReceived()
is not called并且它永远不会从LocationTrack
获取lat-long。
- >> 结果为0.0
解决方案是从服务器发送data only FCM消息,因为您无法从Firebase控制台发送仅数据消息。在这种情况下,即使应用程序处于后台,也会调用onMessageReceived()
。
如果您只想将有效负载发送到特定设备ID,请发送JSON,如:
{
"message":
{
"token":"yourDeviceToken",
"data":
{
"keyFoo":"valueBar"
},
"android":
{
"priority":"high"
"ttl":"3600s"
}
}
}