创建后台服务以始终侦听 firebase 数据库的最佳方法是什么?
What is the best way to create background service to listen firebase database always?
我听说过JobScheduler、WorkerManager、IntentService、AlarmManager 等服务类型。但是我很困惑选择最佳方法来满足各种用例的要求,例如重启、终止应用程序、强制停止
如果您希望服务在后台长时间保持 运行,那么粘性服务是一个好的开始。基本上您将创建一个 class 来扩展service
class 并且您可以使用 START_STICKY
结果将其长期保持 运行。
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//this commandresult makes the service a sticky service
return START_STICKY;
}
//you can create a class that runs on a timer or a loop
// inside this service and it will continue running until the OS or user kills it
// create a timer then query your database inside this class and send out
//notifications accordingly
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
来源:https://www.tutorialspoint.com/android/android_services.htm
我听说过JobScheduler、WorkerManager、IntentService、AlarmManager 等服务类型。但是我很困惑选择最佳方法来满足各种用例的要求,例如重启、终止应用程序、强制停止
如果您希望服务在后台长时间保持 运行,那么粘性服务是一个好的开始。基本上您将创建一个 class 来扩展service
class 并且您可以使用 START_STICKY
结果将其长期保持 运行。
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//this commandresult makes the service a sticky service
return START_STICKY;
}
//you can create a class that runs on a timer or a loop
// inside this service and it will continue running until the OS or user kills it
// create a timer then query your database inside this class and send out
//notifications accordingly
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
来源:https://www.tutorialspoint.com/android/android_services.htm