Home > Back-end >  How to start Flutter app as a background service on system startup
How to start Flutter app as a background service on system startup

Time:08-08

I'm wanting to automatically run my flutter application's background services as soon as the mobile is rebooted.

I implemented the following Solution, but it's throwing some errors


AndroidStudioProjects\db_app\android\app\src\main\kotlin\com\example\laravel_login\MainActivity.kt: (14, 22): Unresolved reference: Uri

AndroidStudioProjects\db_app\android\app\src\main\kotlin\com\example\laravel_login\MainActivity.kt: (14, 28): Unresolved reference: Uri

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

If you know any alternative, please help. Thank you.

MainActivity.kt

package com.example.laravel_login
import android.os.Bundle
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
import android.content.BroadcastReceiver
import android.content.Context;
import android.content.Intent;
class MainActivity: FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var REQUEST_OVERLAY_PERMISSIONS = 100
        if (!Settings.canDrawOverlays(getApplicationContext())) {
            val myIntent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            val uri: Uri = Uri.fromParts("com.example.laravel_login.BootReceiver", getPackageName(), null)
            myIntent.setData(uri)
            startActivityForResult(myIntent, REQUEST_OVERLAY_PERMISSIONS)
            return
        }
    }
}

class BootReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
            val i = Intent(context, MainActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(i)
        }
    }
}

AndroidManifest.xml

<!--       app auto restart on phone restart -->
<receiver
            android:enabled="true"
            android:exported="true"
            android:name="com.example.laravel_login.BootReceiver"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

  </receiver>
<!-- app auto restart on phone restart -->

CodePudding user response:

Add this to the imports of MainActivity.kt and you're good to go.

import android.net.Uri
  • Related