Я создаю приложение отслеживания местоположения.
«Живое» местоположение будет загружено в базу данных Firebase, а затем использовано для отображения текущего местоположения пользователей на карте.
Я уже исправил несколько ошибок, но сейчас не могу продолжить, потому что приложение сборки вылетает по неизвестным причинам.
Я подключил свое приложение к службе Firebase через Android Studio.
Когда я запускаю приложение, все работает нормально. Я должен дать разрешение на местоположение, и после этого приложение просто падает.
Этого не было до того, как я добавил службу Firebase.
Меня спросили о разрешении местоположений, и когда я закодировал приложение, оно закрылось на заднем плане, просто отображая уведомление о том, что отслеживание местоположения выполняется.
Я не получаю абсолютно никаких ошибок или предупреждений при сборке или синхронизации приложения.
Код из TrackerService.java прилагается
Надеюсь, у кого-то есть идея, моя голова сейчас пуста.
Я впервые работаю с «внешним» сервисом, таким как firebase:)
public class TrackerService extends Service {
private static final String TAG = TrackerService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {return null;}
@Override
public void onCreate() {
super.onCreate();
buildNotification();
loginToFirebase();
}
private void buildNotification() {
String stop = "stop";
registerReceiver(stopReceiver, new IntentFilter(stop));
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
// Create the persistent notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_text))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.ic_tracker);
startForeground(1, builder.build());
}
protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "received stop broadcast");
// Stop the service when the notification is tapped
unregisterReceiver(stopReceiver);
stopSelf();
}
};
private void loginToFirebase() {
// Authenticate with Firebase, and request location updates
String email = getString(R.string.firebase_email);
String password = getString(R.string.firebase_password);
FirebaseAuth.getInstance().signInWithEmailAndPassword(
email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){
@Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "firebase auth success");
requestLocationUpdates();
} else {
Log.d(TAG, "firebase auth failed");
}
}
});
}
private void requestLocationUpdates() {
LocationRequest request = new LocationRequest();
request.setInterval(10000);
request.setFastestInterval(5000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
final String path = getString(R.string.firebase_path) + "/" + getString(R.string.transport_id);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
// Request location updates and when an update is
// received, store the location in Firebase
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
Location location = locationResult.getLastLocation();
if (location != null) {
Log.d(TAG, "location update " + location);
ref.setValue(location);
}
}
}, null);
}
}
}
Редактировать: Я проверил свой протокол LogCat, и у меня есть неверный канал для сервисного уведомления.
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1855)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6981)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
Нужно ли создавать канал уведомлений для этого?
Я знаю, где возникает ошибка, но не знаю, как правильно решить проблему!?
2nd Edit: @ Алекс Мамо, спасибо за «подсказку», я был слеп и нуждался в этом небольшом толчке в правильном направлении.
Теперь я успешно создал канал NotificationChannel и назначил моему уведомлению канал. Функция теперь работает как задумано!
Огромное спасибо:)