4

我正在创建一个需要始终通过 TCP 套接字连接的应用程序。我的应用程序在连接方面已经运行良好,但是当它被发送到后台时,android 系统最终会终止该进程。这会导致它与服务器断开连接。

我一直在寻找一种方法来始终保持应用程序处于活动状态,但没有找到任何东西。有人能告诉我最好的方法是什么,这样我的应用程序在后台时不会关闭,或者,除非它关闭,否则让它自行重启?我从这个开始,让我头疼:S

编辑这是我的代码的一部分:

  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;
  }

不过,该应用程序似乎在启动时被冻结。我没有很多经验,所以也许我的错误很简单,我没有注意到。

4

5 回答 5

3

使用服务并通过startService(). 它将一直运行,直到 Android 停止它以获取资源

一些关于服务的文档:

  1. http://developer.android.com/reference/android/app/Service.html
  2. http://developer.android.com/guide/components/services.html
于 2012-11-23T18:59:08.467 回答
0

用户服务。服务用于在后台执行长时间运行的操作,例如在与服务器的连接中发送/接收数据。

于 2012-11-23T19:00:07.873 回答
0

查看Android的Service类。但请注意,aService不是单独的线程,它只是应用程序线程的一部分,操作系统在创建和销毁方面的处理方式不同。

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

于 2012-11-23T19:00:25.117 回答
0

The nature of OS is as such, that is it is supposed to kill background processes because of limited memory resources i guess . Maybe you should check out Watchdog its some kind of background process manager . I am not that used to the android system but this is what i could find from my research . Hope that helps :)

Maybe this will help you :

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

于 2012-11-23T19:07:46.030 回答
0

As the others said, the straight answer to you question is to host a thread that keeps the connection alive into a service.

However I want to remember you that you are in a resource limited environment, where having a persistent connection in background (with the overhead of the tcp protocol) may result into battery drain and angry users.

You should ask yourself if you really want to keep the connection persistent forever, or for a limited amount of time, or just after some events that might be triggered by a gcm message or if you could just go for polling, maybe using an inexact alarm .

Another option would be to establish the connection only when you application is in foreground. Anyway, it certainly depends on what you want to do with your application.

于 2012-11-24T00:02:53.130 回答