简体   繁体   English

使用Thread.sleep()暂停和恢复应用程序

[英]Using Thread.sleep() for pausing and resuming app

Hi, 嗨,
In my app im trying to use Thread.sleep(100) to pause my thread, while its backgrounded in order to use less cpu, but it freezes when I open it back up. 在我的应用程序中我试图使用Thread.sleep(100)暂停我的线程,而它的后台为了使用更少的CPU,但它冻结时,我打开它备份。
I realized that onResume is not being called when I reopen the app. 我意识到当我重新打开应用程序时, onResume没有被调用。

Any ideas why? 有什么想法吗?

public void onPause() {
        pause = true;
        Log.d("mSTATE","THREADPAUSE");
    }

public void onResume() {
    pause = false;
        running = true;
       Log.d("mSTATE","THREADRESUME");
    }
public void run() {

    while(running){
         while(pause && running){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
         }

         while (!pause && running) {
             Canvas c = null;
             try {
                 c = sHolder.lockCanvas(null);
                 synchronized (sHolder) {
                     doDraw(c);
                     powerUps();
                 }
             } finally {
                 if (c != null) {
                     sHolder.unlockCanvasAndPost(c);
                 }
             }
         }
    }
         Log.d("mState","EndofRun");              
}     

When you put your thread to sleep you are also blocking the UI thread thus leading to freezing of your application. 当您将线程置于睡眠状态时,您也会阻止UI线程,从而导致应用程序冻结。

You need to check the Threads in Android way for the best performance. 您需要以Android方式检查线程以获得最佳性能。

http://developer.android.com/resources/articles/painless-threading.html http://developer.android.com/resources/articles/painless-threading.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM