Android -Starting Service at Boot Time

后端 未结 9 1760
一个人的身影
一个人的身影 2020-11-22 16:12

I need to start a service at boot time. I searched a lot. They are talking about Broadcastreceiver. As I am new to android development, I didn\'t get a clear picture about s

9条回答
  •  感动是毒
    2020-11-22 16:39

    To Restart service in Android O or more ie OS >28 Use this code KOTLIN VERSION 1) Add permission in manifest

    
    

    2) Create a Class and extend it with BroadcastReceiver

    import android.content.BroadcastReceiver
    import android.content.Context
    import android.content.Intent
    import android.os.Build
    import android.util.Log
    import androidx.core.content.ContextCompat
    
    
    
    class BootCompletedReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, arg1: Intent?) {
            Log.d("BootCompletedReceiver", "starting service...")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                ContextCompat.startForegroundService(context, Intent(context, YourServiceClass::class.java))
            } else {
                context.startService(Intent(context, YourServiceClass::class.java))
            }
        }
    }
    

    3) Declare in Manifest file like this under application tag

    
            
                
                
            
        
    

提交回复
热议问题