0

I'm trying to create a service which will run a socket for receiver data when the app is closed.

According to this thread on Github Flutter should provide an abstraction for background execution, flutter doesn't have an abstraction that executes a code in the background, so I'm writing a native code.

The service opens up correctly, but as soon as the app is closed, it gets moved to cache services and after approximately 5 minutes it is ended.

I found this background_service MainActivity.java, but I'm not using the notification example contained in that repository. (The service contained in this repository also gets terminated once the app is closed.

The example plugin for this article as well.

I still don't have a concrete plan to make the socket connection in the service. I actually would like to call the socket_io_client function within the service, sort of like a callback, but I'm not sure if it will work.

So I just want to know if it is possible to keep the service running after the app is closed. If yes, how?

MainActivity.java

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "com.retroportalstudio.www.background_service";

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

        Intent forService = new Intent(this, MyService.class);
        forService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                if (methodCall.method.equals("startService")) {
                    startService(forService);
                    result.success("Service Started");

                }

            }
        });
    }
}
public class MyService extends Service {
    //  @Override
    //  public int onStartCommand(Intent intent, int flags, int startId) {
    //      return START_STICKY;
    //  }

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

0 Answers0