2016-06-14 49 views
2

我的应用程序每秒都会发出一个重复请求 - 要求服务器提供新数据,如果有这种情况 - 它会唤醒设备并运行主应用程序。 (这是由用户提出的要求,他们不关心电池的使用情况,每秒运行一次,这是高度关键操作) (用户可以改变设置的任何帮助)服务没有唤醒设备,因为它应该是

我curently试图通过使用来实现这一点无论AlarmManagerSystem.Threading.Timer(既试过),但每次我与后续问题结束时间:

  • 的装置停止请求,在一些服务器当它睡觉时,并在一些看起来像随机时间,它恢复了短暂的工作。为什么会发生这种情况,以及如何解决这个问题?

(OS:机器人5.x的)

(使用AlarmManager)

Calendar cal = Calendar.getInstance(); 
     cal.add(Calendar.SECOND, ConfigReader.serviceRepeatInterval); 

     Intent intent = new Intent(this, SaleService.class); 

     PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); 

     AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 

     alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), ConfigReader.serviceRepeatInterval, pintent); 

从服务的变化的代码从服务的Java中的变化的代码是C#( Xamarin)使用计时器。

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) 
     { 

      if(_powerManager == null) 
      { 
       _powerManager = (PowerManager)this.GetSystemService(PowerService); 
       _wakeLock  = _powerManager.NewWakeLock(WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, mySaleServiceWakeLock); 
       vibrator  = (Vibrator)this.GetSystemService(Context.VibratorService);     
      } 

      timer = new System.Threading.Timer(getCurrentPendingObjects, null, timerRepeatInterval, Timeout.Infinite); 

      return StartCommandResult.Sticky; 
     } 
+0

发布您的代码,您设置闹钟的地方 – earthw0rmjim

回答

1

使用AlarmManager.ELAPSED_REALTIME_WAKEUPAlarmManager.RTC_WAKEUP会在报警触发时唤醒设备。

的装置停止请求服务器在某些时候当它睡觉 和一些外观类似随机的时间来恢复它是一个短期工作。 为什么会发生这种情况,以及如何解决这个问题?

这可能是因为您的PendingIntent正在调用Service。这样设备可以在onStartCommand()执行之前回到睡眠状态。 您应该使用BroadcastReceiver,而不是(因为WakeLock期间onReceive()“保证”),AQUIRE一个WakeLockonReceive(),启动Service从那里,你的WakeLockService,释放适当的时候。

尽管在延长的时间段内(甚至在设备处于睡眠状态时)每秒重复一次请求似乎是一种糟糕的设计。它会很快耗尽电池。

你应该重新考虑你的实现,也许使用某种回调机制,或者至少增加请求之间的间隔(显着)。