Skip to content

Background service on Android with java using flutter project

I am new to flutter, I am trying to create a service in the background when starting Android occupying the main java class since in flutter it cannot be done, so I want to start a service in its background from here

package com.example.flutter_app_services;



import android.os.Bundle;

import io.flutter.embedding.android.FlutterActivity;


public class MainActivity extends FlutterActivity {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }


}

I have seen many queries with the following code: Java class


import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;

public class ServiceBack extends Service {

    public Context context = this;
    public Handler handler = null;
    public static Runnable runnable = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "Start", Toast.LENGTH_LONG).show();

        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                Toast.makeText(context, "In Run....", Toast.LENGTH_LONG).show();
                handler.postDelayed(runnable, 10000);
            }
        };

        handler.postDelayed(runnable, 15000);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Stop", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "initialized", Toast.LENGTH_LONG).show();
    }
}

Start Service

startService(new Intent(this,ServiceBack.class));

This is my AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.flutter_app_services">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

   <application
        android:label="flutter_app_services"
        android:icon="@mipmap/ic_launcher">

       <service android:enabled="true" android:name=".ServiceBack" />
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>


        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

The main problem is that I don’t know how to implement it in the “Flutter Activity”. I am trying to make a service that starts in BOOT and when I close the main application the service continues in the background (it is important that it does not stop), but none of this works either, I need help, I have looked everywhere and nothing. I use the Android 11 operating system.

Answer

You won’t get what you want. In Android, there are 2 types of services- Foreground and Background.

Background services can be killed at any time. They will be killed by the OS a few minutes after starting. They’re meant for short duration tasks in the background that need a valid Android Context object.

Foreground services can be killed at any time. They show a notification to the user that the service is running, so the user knows what’s going on at all times. Foreground services are lower on the kill list than background services so they won’t be killed immediately, but the OS can and will kill them for resources whenever it thinks it needs them. They are not reliable.

There is no reliable way to run a background service like you would on a PC. Instead, you need to architect your code to work on an event driven basis so that it can respond to OS or time events and do work as needed, rather than waiting around for a request to be made.

More focused advice on how to do that would require a lot more details about what you’re trying to do.