How can I save the application in the background?

I am creating an application in which I always need to connect through a TCP socket. My application is already working well in terms of connectivity, but when it goes to the background, the Android system ultimately kills the process. This makes it disconnect from the server.

I was looking for a way to always keep the application alive, but found nothing. Can someone tell me what would be the best way to do this so that my application does not close when it was in the background, or if it was forbidden, force it to restart if it is closed? I start with this and produce a headache: S

EDIT This is part of my code:

public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); new Thread(new Runnable() { public void run() { Playit(); } }).start(); return START_STICKY; } 

At startup, the application seems to be frozen. I do not have much experience, so perhaps my mistake is simple, and I did not notice it.

+4
source share
5 answers

Use the Service and start it through startService() . It will work until Android stops it for resources

Some service documentation:

+3
source

User a Service . Services are used to perform lengthy operations in the background, such as sending / receiving data in connection with a server.

0
source

Take a look at the Android Service class. Note that a Service NOT a separate thread, it is just part of your application thread, it is simply handled by the OS in terms of creation and destruction.

If you need an extra thread, you can, of course, create it in Service .

0
source

The nature of the OS as such, that is, it should kill background processes due to limited memory resources, I think. Perhaps you should check Watchdog with your background process manager. I'm not used to the Android system, but this is what I could find in my research. Hope this helps :)

Perhaps this will help you:

http://lifehacker.com/5608163/watchdog-monitors-your-android-for-run+away-processes

0
source

As others have said, the direct answer to your question is to host a thread that supports the connection in the service.

However, I want to remember that you are in a resource-limited environment where a permanent connection in the background (with tcp protocol overhead) can lead to battery drainage and angry users.

You should ask yourself if you really want to keep a permanent connection forever or for a limited time or immediately after some events that may be triggered by a gcm message, or if you can just go to the polling, possibly using an inaccurate signal .

Another option is to establish a connection only when the application is in the foreground. In any case, it definitely depends on what you want to do with your application.

0
source

Source: https://habr.com/ru/post/1448013/


All Articles