Android:屏幕锁定时服务停止,为什么?

时间:2016-01-11 10:36:45

标签: android timer android-service

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

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

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

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

有没有人知道在这种情况下计时器是否会停止?或服务停止?

会感激一些帮助! : - )

2 个答案:

答案 0 :(得分:3)

这是因为您的设备开始入睡。强烈建议将此其他实现用于此类过程: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 ...
}

答案 1 :(得分:0)

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

相关问题