0

I've looked for the solution of my problem but I've failed in finding a suitable answer.

I've been trying to develop an Android application with heavy asyncronous networking capabilities. The problem is syncronizing async parts at some point.

What I want to do is to create a service, download big amounts of data from several links, parse them as soon as I get a response and finally show them IF the activity is present. The service should be functional even when the application is closed and should be able to sync itself with the corresponding views in the activity. User should be pause, stop or continue network tasks from within the activity. Also, the activity or the service can exist independent from each other.

I've thought about buffering the network responses via a queue implementation and reading from that buffer when the activity is present.

One example for such operations could be the uTorrent application. It leaves a notification while running the service and as soon as you touch it, the application starts an activity and shows the situation of the torrents. I aim to build a similar structure.

Problems:

  • The activity can easily read from that buffer but after that how will it know that there are new items in the buffer?

  • How will the service know if the application is terminated while reading the buffer or not?

  • There is a GenerateSummary function for the completed downloads but where will it read the finished network operation data?

TL,DR: What is the best practice while executing network tasks with coexisting independent user interface for an Android application?

1 Answer 1

1

To keep the service always alive even the activity has been closed, you have the start the service as foreground. That leaves a notification on top. Now bind your service to your activity when the activity is visible and unbind on closing the activity. By this way, you will always have full control on your service.

To start foreground

@Override
public void onCreate() {
    super.onCreate();
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("Launcher");
    Notification notification = builder.build();
    startForeground(545, notification);
}

To bind your service to your activity Read this page for service bind example http://www.techotopia.com/index.php/Android_Local_Bound_Services_%E2%80%93_A_Worked_Example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.