Android 没有服务 运行

Android service not running

我按照官方文档实施了一项服务,该服务 运行 无限期地检查 Firebase 数据库更改并发送通知。即使应用程序被终止,我也希望服务 运行。我查看了其他 Stack Overflow 帖子,但大多数帖子都是从 Activity 开始他们的服务,但我不想这样做,因为我希望服务 运行 即使应用程序不是 started/running。该服务根本不是 运行ning,我不确定为什么。提前致谢。

AndroidManifest.xml:

  <service android:name=".service.DbService" />

代码:


import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.database.*

class DbService : Service() {

    private lateinit var dbRef: DatabaseReference

    override fun onCreate() {
        Log.d("Service", " +++++++++++++++++++++++++++++++++++++++++++++++++ onCreate");
//        FirebaseApp.initializeApp(this)
        dbRef = FirebaseDatabase.getInstance().reference.child("messeges")
        createNotificationChannel()
        dbRef.addChildEventListener(dbListener)
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("Service", " +++++++++++++++++++++++++++++++++++++++++++++ onStartCommand");
        return START_STICKY
    }

    override fun onDestroy() {
        dbRef.removeEventListener(dbListener)
    }

    private val dbListener = object : ChildEventListener {
        override fun onCancelled(error: DatabaseError) {
            TODO("Not yet implemented")
        }

        override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
            TODO("Not yet implemented")
        }

        override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
            with(NotificationManagerCompat.from(applicationContext)) {
                // notificationId is a unique int for each notification that you must define
                notify(DBEventID, notification())
            }
        }

        override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
            Log.d("Service", " +++++++++++++++++++++++++++++++++++++++++++ onChildAdded");
            with(NotificationManagerCompat.from(applicationContext)) {
                // notificationId is a unique int for each notification that you must define
                notify(DBEventID, notification())
            }
        }

        override fun onChildRemoved(snapshot: DataSnapshot) {
            with(NotificationManagerCompat.from(applicationContext)) {
                // notificationId is a unique int for each notification that you must define
                notify(DBEventID, notification())
            }
        }
    }

    private fun notification(): Notification {

        // Create an explicit intent for an Activity in your app
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_round_test)
            .setLargeIcon(
                BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_round_test)
            )
            .setContentTitle("test")
            .setContentText("lalala test")
            .setPriority(NotificationCompat.PRIORITY_MAX)
//            .setDefaults(Notification.DEFAULT_ALL)
            //.setLights(Color.BLUE, 500, 500)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()
    }

    // you should execute this code as soon as your app starts
    private fun createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //     val name = getString(R.string.channel_name)
            // val descriptionText = getString(R.string.channel_description)
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel =
                NotificationChannel(CHANNEL_ID, "channel name (change)", importance).apply {
                    description = "notification descripton"//descriptionText
                    enableLights(true)
                    lightColor = getColor(R.color.colorPrimary)
                }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    companion object {
        private const val CHANNEL_ID = "Listing Update notifier"
        private const val DBEventID = 12345
    }
}

运行 后台检查服务器更新的服务效率不高。多个设备将发出不必要的请求来检查服务器更新,这非常低效且浪费电池。

我发现最有效的方法是使用 Firebase Functions。我编写了服务器端 js 代码来检查传入请求的更新,并在需要时向特定设备发送通知。