1小时后延迟无效

时间:2016-07-19 09:32:02

标签: java android handler

我在服务中使用hanfler在android延迟后调用方法。它不适用于长时间延迟,但相同的代码适用于小延迟。

Handler mHandler; 
Runnable runnable; 

mHandler = new Handler(); 
runnable=new Runnable() { 
    @Override 
    public void run() { 
        Log.i("START SERVICE", "START SERVICE:3 Call to Check Status is called"); 
        callToCheckStatus(); 
        mHandler.postDelayed(this, 1000*60*60); 
    } 
};
mHandler.postDelayed(runnable, 1000*60*60);

在某些博客上,我发现当设备进入深度睡眠状态时,它无效。那么在Android中调用方法的正确方法是什么。

1 个答案:

答案 0 :(得分:0)

试试这个

public static void intertiAdsStartTimer(Context cnxt) {
    timer = new Timer();
    initializeTimerTask(cnxt);
    //timer.schedule(timerTask, delayTime, repeatedTime);
    timer.schedule(timerTask, 0, Integer.parseInt("7") * 60 * 1000); //
}

public static void initializeTimerTask(final Context cnxt) {
    try {
        final Handler handler = new Handler(Looper.getMainLooper());
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            //call your method
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
    }
}

OR

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 10s = 10000ms

    }
}, 10000);