1

What is the best way to persistently keep an Android Nearby Connection running in the background over multiple activities in the app?

I did some research about Android Services and IntentService, but I feel that neither is designed to run constantly in the background (e.g. if no data is transferred and the connection is idle).

As all available samples show the use of Nearby Connections in a single Activity, I don't know how to adapt it to a multi-activity application.

Wilder Pereira
  • 2,249
  • 3
  • 21
  • 31
StackHelge
  • 75
  • 1
  • 8

1 Answers1

1

The main way I've seen other developers doing to solve that, and that I also did in a recent project, is by using a Singleton for the connection.

You can create a Singleton for the GoogleApiClient in the Application class and reuse the same connection in different activities.

There are some ways you can handle the message callbacks differently for each of the activities. One approach is by creating adapters for the api's listeners and make mutable properties you can use and change inside those listeners according to your current activity.

This blog post shows an implementation using a similar approach.

Another workaround to this would be by using an activity with multiple fragments instead of multiple activities. But that's not exacly what you asked.

Wilder Pereira
  • 2,249
  • 3
  • 21
  • 31