How to automatically launch an app when an Android phone boots up for Kotlin

55 Views Asked by At

Hello awesome developers! As you can see, I'd like to ensure my application starts when the phone boots up. Everything else is functioning correctly; I receive toasts and background processes are working. However, my application fails to run. What could be the issue, and how can I fix it? Thank you.

class BootCompleteReceiver : BroadcastReceiver() {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == Intent.ACTION_BOOT_COMPLETED) {
            Toast.makeText(context, "Boot Completed", Toast.LENGTH_LONG).show()
            val mainIntent = Intent(context, MainActivity::class.java)
            mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context?.startActivity(mainIntent)
        }
    }
}
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

     <receiver
         android:name=".BootCompleteReceiver"
         android:exported="false"
             android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
         <intent-filter android:priority="1000">
         <action android:name="android.intent.action.BOOT_COMPLETED" />
         <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
         </receiver>

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AutoBootTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting("Android")
                }
            }

        }


    }

}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    AutoBootTheme {
        Greeting("Android")
    }
}
0

There are 0 best solutions below