我正在开发一个跟踪设备位置并将该位置记录到Firebase中的应用程序,该应用程序已成功连接到Firebase服务器,但是没有有关该设备位置的数据。谁能找到我的解决方案?以及如何查看Firebase中的存储数据。下面我在我的项目中使用的代码
TrackingService.java:
public class TrackingService extends Service {
private static final String TAG = TrackingService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startForeground();
else
startForeground(1, new Notification());
loginToFirebase();
}
//Create the persistent notification//
private void startForeground() {
String NOTIFICATION_CHANNEL_ID = "com.example.location2";
String channelName = "location2";
String stop = "stop";
registerReceiver(stopReceiver, new IntentFilter(stop));
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
//.setSmallIcon(R.drawable.icon_1)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.tracking_enabled_notif))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.tracking_enabled)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Unregister the BroadcastReceiver when the notification is tapped//
unregisterReceiver(stopReceiver);
//Stop the Service//
stopSelf();
}
};
private void loginToFirebase() {
//Authenticate with Firebase, using the email and password we created earlier//
String email = getString(R.string.test_email);
String password = getString(R.string.test_password);
//Call OnCompleteListener if the user is signed in successfully//
FirebaseAuth.getInstance().signInWithEmailAndPassword(
email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(Task<AuthResult> task) {
//If the user has been authenticated...//
if (task.isSuccessful()) {
//...then call requestLocationUpdates//
requestLocationUpdates();
} else {
//If sign in fails, then log the error//
Log.d(TAG, "Firebase authentication failed");
}
}
});
}
//Initiate the request to track the device's location//
private void requestLocationUpdates() {
LocationRequest request = new LocationRequest();
//Specify how often your app should request the device’s location//
request.setInterval(10000);
//Get the most accurate location data available//
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
final String path = getString(R.string.firebase_path);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
//If the app currently has access to the location permission...//
if (permission == PackageManager.PERMISSION_GRANTED) {
//...then request location updates//
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
//Get a reference to the database, so your app can perform read and write operations//
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
Location location = locationResult.getLastLocation();
if (location != null) {
//Save the location data to the database//
ref.setValue(location);
}
}
}, null);
}
}
}
mainactivity.java:
public class MainActivity extends Activity {
private static final int PERMISSIONS_REQUEST = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Check whether GPS tracking is enabled//
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
finish();
}
//Check whether this app has access to the location permission//
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
//If the location permission has been granted, then start the TrackerService//
if (permission == PackageManager.PERMISSION_GRANTED) {
startTrackerService();
} else {
//If the app doesn’t currently have access to the user’s location, then request access//
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
//If the permission has been granted...//
if (requestCode == PERMISSIONS_REQUEST && grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//...then start the GPS tracking service//
startTrackerService();
} else {
//If the user denies the permission request, then display a toast with some more information//
Toast.makeText(this, "Please enable location services to allow GPS tracking", Toast.LENGTH_SHORT).show();
}
}
//Start the TrackerService//
private void startTrackerService() {
startService(new Intent(this, TrackingService.class));
//Notify the user that tracking has been enabled//
Toast.makeText(this, "GPS tracking enabled", Toast.LENGTH_SHORT).show();
//Close MainActivity//
finish();
}
}
我不确定这是否是问题,但请告诉我是否可行。
尝试像这样启动服务:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
}else{
startService( intent)
}