Android: 锁屏后服务停止,为什么?

Android: Service stops when screen locks, why?

我使用一项服务,在这项服务中我有一个计时器,它每分钟向我的 TCP/IP-Server 发送一条消息。

public void keepAlive() {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
                    String message = gson.toJson(new StillAlive(Mode.STILLALIVE));
                    sendMessage(message);
                    Log.d("TCP-SEND", message);
                } catch(Exception e) {
                    Log.e("TCP1", e.getMessage());
                }
            }
        }, 60000, 60000);
    }

但是当我的手机 phone 锁定时。或者我按下按钮关闭显示,我的服务停止发送这些消息。

我不确定的是,如果服务停止,当关闭显示器时,或者是否由于我不知道的任何原因只是计时器停止。

有谁知道在这种情况下计时器是否会停止?或者服务停止了吗?

非常感谢您的帮助! :-)

这是因为您的设备开始休眠。强烈建议对此类过程使用其他实现:AlarmManager

看起来像这样(这是我的代码的一部分):

private static AlarmManager am;

//....
@SuppressLint("NewApi")
public static void startByAlarm(Context ctx, boolean wakeup, long nexttime, boolean autoStart)
    {
PendingIntent pi = wakeup? PendingIntent.getBroadcast(ctx, _.intentalarm, intent, PendingIntent.FLAG_CANCEL_CURRENT):
            PendingIntent.getService(ctx, _.intentalarm, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.KITKAT){
        am.setExact(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
    } else{
        am.set(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
    }
//or am.setRepeating ...
}

看看This answer by jscharf,这可能对您有帮助,但您必须对此保持警惕,因为这是一项耗电任务。