Flutter and Services

Flutter and Services

Best service works !!!

How to interact with Services in android ? Hmm….


Although Flutter is quite powerful, but sometimes you need to interact with platform specific things…(Flutter and services)

This article focuses on how to get data from the android Services

Note: This code is not compatible with iOS…

What are Services ?

Service is an application component that can perform long-running operations in the background, and it doesn’t provide a user interface. For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

Started Service : 

A started service is one that another component starts by calling startService(), which results in a call to the service’s onStartCommand() method.

When a service is started, it has a lifecycle that’s independent of the component that started it. The service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is complete by calling stopSelf(), or another component can stop it by calling stopService().

Flutter and Services…
Flutter and Services…

Creating a Service…..

  1. Open the Flutter Project in Android Studio….
Flutter and Services…
Flutter and Services…

2. Create service in Android Studio…

Create a Service….
Create a Service….

This takes care of adding Service in the Android Manifest.xml….

Note : We will be selecting the Service here…

3. In the onStartCommand, we can implement our custom logic..In our case, we have added the following code :

MyThread myThread = new MyThread();

Below is the code for MyThread class : 

public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 1; i++) {
try {
Intent intent = new Intent();
intent.putExtra("DATAPASSED", i);
_currentValue = i;
} catch (InterruptedException e) {
// TODO Auto-generated catch block

Things to Note : 

  1. The value is passed back via Intent using key as “DATAPASSED”
  2. Once the logic is completed, stopSelf is called…
  3. We have used intent.setAction() [which sets the general action to be performed, to be used by BroadCast Receiver]

Get data in Activity from Service….

  1. Create a BroadcastReceiver in the Activity Class as :
private class MyReceiver extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {

int datapassed = arg1.getIntExtra("DATAPASSED", 0);
"Value from service !!\n"
+ "Data passed: " + String.valueOf(datapassed),

Things to Note :

  • While extending a class to BroadcastReceiver, we need to implement onReceive.
  • We get the intent as “DATAPASSED” and the value as int (As we defined in the Service (Look above section))

2. Register the BroadCastReceiver in onStart as :

myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
registerReceiver(myReceiver, intentFilter);

3. Unregister the BroadCastReceiver in onStop as :

if (myReceiver != null) {

Enter Flutter….(Flutter and services)

We need a mechanism to call the service from Flutter…..

  1. Change the MainActivity to implement MethodChannel…
public class MainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler

2. Override the method onMethodCall and make changes as:

public void onMethodCall(MethodCall call, MethodChannel.Result result) {
try {
if (call.method.equals("connect")) {
keepResult = result;
} else if (serviceConnected) {
if (call.method.equals("start")) {
String _data = SimpleService.helloFromService();
} else {
result.error(null, "App not connected to service", null);
} catch (Exception e) {
result.error(null, e.getMessage(), null);

Things to Note :

  • We are exposing “connect” and “start” methods to Flutter framework..
  • On the call to “connect”, connectToService function is called, which activates the service (Created above)….
private void connectToService() {
if (!serviceConnected) {
Intent service = new Intent(this, SimpleService.class);
serviceConnected = true;
} else {
if (keepResult != null) {
keepResult = null;
  • This calls startService() which is important to start a service…

3. In the onCreate of the MainActivity, include the following line:

new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(this::onMethodCall);

4. Important variables :

static final String TAG = "Main Activity.....";
static final String CHANNEL = "com.example.services_demo/service";
MyReceiver myReceiver;
MethodChannel.Result keepResult = null;
boolean serviceConnected = false

Things to Note :

  • Value of variable CHANNEL, should be same in the Flutter (see below)..
  • This CHANNEL, registers the Android Native Code with the Flutter…

Dart / Flutter Side :

  1. Initialize platform variable as
static const platform = MethodChannel('com.example.services_demo/service');

Note: This value is same as the variable CHANNEL (see above)…

2. In the initState,

void initState() {

and inside connectToService

Future<void> connectToService() async {
try {
await platform.invokeMethod<void>('connect');
print('Connected to service');
} on Exception catch (e) {

Note : ‘connect’ is the same value as declared in the MainActivity ‘s OnMethodCall

3. After we have successfully connected to the service, now we can receive any data from it…

Future<String> getDataFromService() async {
try {
final result = await platform.invokeMethod<String>('start');
return result;
} on PlatformException catch (e) {
return 'No Data From Service';

Note : ‘start’ is the same value as declared in the MainActivity ‘s OnMethodCall

Source Code : https://github.com/AseemWangoo/services_demo