2013-10-05 116 views
1

我正在测试surfaceView,基本上应用程序jsut更改背景的颜色。Android:surfaceView无法从暂停恢复活动()

该应用程序以没有问题开始,但当我“暂停”活动并“恢复”它时,应用程序在“暂停()”方法循环中被阻止。

这是我的代码:

import java.util.Random; 

import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Canvas; 
import android.util.Log; 
import android.view.Menu; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class SurfaceViewTest extends Activity { 
    FastRenderView renderView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_surface_view_test); 
     renderView= new FastRenderView(this); 
     setContentView(renderView); 
    } 

    protected void onResume() { 
     super.onResume(); 
     renderView.resume(); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     renderView.pause(); 
    } 

    public class FastRenderView extends SurfaceView implements Runnable { 
     Thread renderThread=null; 
     SurfaceHolder holder; 
     volatile boolean running=false; 

     Random rand= new Random();      //random number creator---- 

     public FastRenderView(Context context) { 
      super(context); 
      holder=getHolder();   //<<-check the this statement 
     } 
     public void resume() { 
      Log.d("ZR", "in resume"); 
      running=true; 
      renderThread=new Thread(this); 
      renderThread.start(); //<<<--AVVIA IL THREAD 
     } 
     @Override 
     public void run() { 
      Log.d("ZR", "in running"); 
      while(running){ 
       try { 
        Thread.sleep(500); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       if(!holder.getSurface().isValid()) 
        continue; 
       Canvas canvas = holder.lockCanvas(); 
       canvas.drawRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)); 
       holder.unlockCanvasAndPost(canvas); 
      } 
     } 
     public void pause() { 
      running = false; 
      Log.d("ZR", "in pause"); 
      while(true){ //<<<<<<<<<<<<<<CHECKKKKKK 
       try { 
        renderThread.join(); 
        Log.d("ZR", "in pause end"); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

回答

1

while(true)循环没有了断将永远不会在方法pause()停止。我希望在成功加入渲染线程后等待回复(等待直到它结束)

在您的volatile声明中的while循环应该没问题。

+0

使用“break”它有效,不明白为什么在这些例子中没有人使用break? ---> http://stackoverflow.com/questions/3527621/how-to-pause-and-resume-a-surfaceview-thread?rq=1和http://stackoverflow.com/questions/14013468/pausing-线程正确的onpause-and-onresume-with-a-surfaceview-and-thread?rq = 1 – Luther

+0

好问题。你有没有检查过他们中的一个是否曾问过其他问题:-) – jboi