我有一个Handler
,只需在触发后将“触发”写入文件即可。每5秒触发Handler
进行测试。这很奇怪:
当我启动应用程序并且应用程序被预先考虑时,Handler
每5秒正常运行一次。如果应用程序背景并且手机已插入笔记本电脑,我可以通过logcat看到一切正常。但是,当我取下电话线并且应用程序背景(未关闭)时,计时器出现问题!
这是我的代码:
public void trigger()
{
RZTestHandler.removeCallbacks(RZTestTask);
RZTestHandler.postDelayed(RZTestTask, 5000);
}
private Handler RZTestHandler = new Handler();
private Runnable RZTestTask = new Runnable() {
@Override
public void run() {
globalVariables.AppLogging("triggered"); //simply writes to file
Log.d(TAG,"Triggered");
trigger();
}
};
从Activity onCreate()调用:
trigger();
AppLogging方法运行以下代码:
File oFile = new File(filePath);
if (!oFile.exists()) {
oFile.createNewFile();
}
if (oFile.canWrite()) {
BufferedWriter oWriter = new BufferedWriter(new FileWriter(new File(filePath),true));
oWriter.newLine();
oWriter.write (" ###"+new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH).format(new Date())+":Activity:"+sContent +" \n\r");
oWriter.close();
}
输出
19/01/2016 03:26:24 PM:活动:触发
19/01/2016 03:26:29 PM:活动:触发
19/01/2016 03:26:34 PM:活动:已触发
19/01/2016 03:26:39 PM:活动:触发
19/01/2016 03:26:45 PM:活动:已触发
19/01/2016 03:26:50 PM:活动:触发
19/01/2016 03:26:55 PM:活动:已触发
19/01/2016 03:27:00 PM:活动:已触发
19/01/2016 03:27:05 PM:活动:触发//背景和分离
19/01/2016 03:27:14 PM:活动:触发
19/01/2016 03:27:27 PM:活动:已触发
19/01/2016 03:27:33 PM:活动:已触发
19/01/2016 03:27:46 PM:活动:触发//重新附加和前景
19/01/2016 03:27:51 PM:活动:触发
19/01/2016 03:27:56 PM:活动:已触发
19/01/2016 03:28:01 PM:活动:已触发
19/01/2016 03:28:06 PM:活动:已触发
19/01/2016 03:28:11 PM:活动:已触发
19/01/2016 03:28:16 PM:活动:已触发
答案 0 :(得分:0)
我按以下方式创建了一个服务,并使用了PowerManager.WakeLock:
public class PeriodicalTimerService extends Service
{
PowerManager.WakeLock wakeLock;
PowerManager mgr = (PowerManager)MyApplication.getContext().getSystemService(Context.POWER_SERVICE);
public static Handler RZTestHandler = new Handler();
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
PeriodicalTriggerStarter();
return START_STICKY;
}
private Runnable RZTestTask = new Runnable()
{
@Override
public void run()
{
boolean backgrounded = globalVariables.isApplicationSentToBackground();
if(GlobalVariables.IsSignedIn)
{
if (GlobalVariables.DownloadServiceCanStart)
{
GlobalVariables.DownloadServiceCanStart=false;
StartStopService.StartDownloadService(MyApplication.getContext());
}
if (wakeLock!=null && wakeLock.isHeld())
{
wakeLock.release();
}
Repeater();
}
else
{
if (wakeLock != null && wakeLock.isHeld())
{
wakeLock.release();
}
stopSelf();
}
}
};
public void Repeater() {
wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RSZWakeLock");
wakeLock.acquire();
if (RZTestHandler == null)
{
RZTestHandler = new Handler();
}
RZTestHandler.removeCallbacksAndMessages(null);
RZTestHandler.postDelayed(RZTestTask, Long.parseLong(globalVariables.GetSharedStringValue("serviceTimer")));
}
public void PeriodicalTriggerStarter()
{
if (RZTestHandler == null)
{
RZTestHandler = new Handler();
}
RZTestHandler.removeCallbacksAndMessages(null);
RZTestHandler.postAtFrontOfQueue(RZTestTask);
}
}