Android 服务在不到 5 分钟后停止

Android service stops after less than 5 minutes

我正在创建一个需要不断向服务器发送 UDP 数据包的 Android 应用程序。

问题是,2-5分钟后,屏幕熄灭后,服务停止发送数据,直到我重新打开屏幕(也可以在服务器端确认)。

这里是服务启动命令:

startService(new Intent(getBaseContext(), Service.class));

onStartCommand:

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    Toast.makeText(this, "Armed!", Toast.LENGTH_LONG).show();
    (new Thread(new App())).start();
    return START_REDELIVER_INTENT;
}

和 运行 方法,来自 App 线程:

public void run(){
    Vibrator alarm = (Vibrator) MainActivity.getAppContext().getSystemService(Context.VIBRATOR_SERVICE);
    String IP = getWiFiIP(MainActivity.getAppContext());

    while(true){
        while (IP.equals(wifiAddr)){ //Confirm presence on local network, with host
            //Unlocked door
            System.out.println("Started locally!");
            sendData(KEY, hostAddrLocal);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            IP = getWiFiIP(MainActivity.getAppContext());
        }
   }
}

我确定我没有 运行内存不足,我没有其他应用程序,运行在 Galaxy S4 上使用 Lollipop 5.0

是不是因为我在和主activity交互,获取上下文 MainActivity.getAppContext() ?

我尝试了很多东西,包括 STICKY_SERVICE

The problem is that after 2-5 minutes, after the screen is off, the service stops sending data, until I turn the screen back on (can also confirm on the server side).

CPU 很可能已关闭,WiFi 无线电也已关闭。您需要获得一个 WakeLock 和一个 WifiLock 才能使两者保持开机状态。对于使用普通硬件的普通用户来说,一直保持 CPU 和 WiFi 收音机处于开启状态会因为电池耗尽而非常不受欢迎。

Android 被编程为在不活动后入睡。发生这种情况时,它会关闭处理器并不允许任何应用程序进行处理。要成为此规则的例外,您需要持有部分唤醒锁。这样做会导致您使用更多电池,因此请尽量不要将其放置超过需要的时间。