How to make app to run always in background in Flutter

How to make app to run always in background in Flutter?

Sometimes a user may require to run the application always in the background So this time we will go through How to make an app to run always in the background in Flutter.

Are you ready for the same?

How to make the app run always in the background in Flutter?

There isn’t a way to do this directly from flutter right now although that may change at some point – see this bug/feature request. You do have a couple of options though.

The first is to use MethodChannels and simply write the android code you want to create a background service (or if you want it to always be a background service you can probably do that without needing communication from the flutter side).

The second is some combination of these two plugins – android_alarm_manager and android_intent. But that won’t help for all use-cases.

Create a New Flutter project

  • Create BroadcastReceiver class beside MainActivity in android dir.
  • Change MainActivity.java and main.dart and AndroidManifest.xml like this
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application ...>
  <receiver
      android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmBroadcastReceiver"
      android:exported="true">
      <intent-filter>
          <action android:name="dev.fluttercommunity.plus.androidalarmmanager.action.ALARM" />
      </intent-filter>
  </receiver>
  
  <receiver
      android:name="dev.fluttercommunity.plus.androidalarmmanager.RebootBroadcastReceiver"
      android:exported="true">
      <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
  </receiver>
  ...
</application>

MainActivity will look like below

package com.example.flutter_broadcastreceiver_alarmmanager_repeat;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.view.FlutterView;

public class MainActivity extends FlutterActivity {

    private PendingIntent pendingIntent;
    private AlarmManager alarmManager;
    private static  FlutterView flutterView;
    private static final String CHANNEL = "com.tarazgroup";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        flutterView=getFlutterView();
        GeneratedPluginRegistrant.registerWith(this);

        Intent intent = new Intent(this, MyReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 1019662, intent, 0);
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pendingIntent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        alarmManager.cancel(pendingIntent);
    }

    static void callFlutter(){
        MethodChannel methodChannel=new MethodChannel(flutterView, CHANNEL);
        methodChannel.invokeMethod("I say hello every minute!!","");
    }
}

main.dart will look like below

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

<application ...>
  <receiver
      android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmBroadcastReceiver"
      android:exported="true">
      <intent-filter>
          <action android:name="dev.fluttercommunity.plus.androidalarmmanager.action.ALARM" />
      </intent-filter>
  </receiver>
  
  <receiver
      android:name="dev.fluttercommunity.plus.androidalarmmanager.RebootBroadcastReceiver"
      android:exported="true">
      <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
  </receiver>
  ...
</application>
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Alarm Manager Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final int alarmId = 0;
            await AndroidAlarmManager.periodic(
              const Duration(minutes: 5), // Duration between each execution
              alarmId, // Unique ID for this alarm
              printHello, // The function to be executed
              startAt: DateTime.now(), // Start time
              exact: true, // Exact timing
              wakeup: true, // Wake the device if it is asleep
            );
          },
          child: Text('Start Background Task'),
        ),
      ),
    );
  }
}

Define Function

void printHello() {
  final DateTime now = DateTime.now();
  print("[$now] Hello, world!");
}

AndroidManifest.xml will have a code snippet like the below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.flutter_broadcastreceiver_alarmmanager_repeat">

    <application
        android:name="io.flutter.app.FlutterApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="flutter_broadcastreceiver_alarmmanager_repeat">
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:windowSoftInputMode="adjustResize">

            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyReceiver"></receiver>

    </application>

</manifest>

Conclusion

Ensuring your app runs efficiently in the background is crucial for a seamless user experience. At Flutter Agency, we pride ourselves on being one of the best mobile app development agencies, providing expert solutions and support. Partner with us to elevate your app development projects to new heights.

Thanks for Reading !!!

So in this article, we have been through How to make an app run always in the background in Flutter.

Keep Learning !!! Keep Fluttering !!!

Still, need Support for Flutter Development? Do let us know.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields