[英]Android - onPause and onResume
我有随机绘制红色圆圈的代码。 直到我在两个类中都有暂停和恢复方法后,它才起作用。 如果没有 pause 和 resume 方法,屏幕将只是黑屏而不会改变。 为什么我需要onPause
和onResume
方法,为什么在两个类中都需要?
注释代码是所有暂停/恢复方法。
public class RandomCircles extends Activity {
MySurfaceView mySurfaceView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySurfaceView = new MySurfaceView(this);
setContentView(mySurfaceView);
}
/* @Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mySurfaceView.onResumeMySurfaceView();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mySurfaceView.onPauseMySurfaceView();
}*/
class MySurfaceView extends SurfaceView implements Runnable{
Thread thread = null;
SurfaceHolder surfaceHolder;
volatile boolean running = false;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Random random;
public MySurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
surfaceHolder = getHolder();
random = new Random();
}
/*public void onResumeMySurfaceView(){
running = true;
thread = new Thread(this);
thread.start();
}
public void onPauseMySurfaceView(){
boolean retry = true;
running = false;
while(retry){
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
@Override
public void run() {
// TODO Auto-generated method stub
while(running){
if(surfaceHolder.getSurface().isValid()){
Canvas canvas = surfaceHolder.lockCanvas();
//... actual drawing on canvas
int x = random.nextInt(getWidth());
if(getWidth() - x < 100)
x -= 100;
else if(getWidth() - x > getWidth() - 100)
x += 100;
int y = random.nextInt(getHeight());
if(getHeight() - y < 100)
y -= 100;
else if(getHeight() - x > getHeight() - 100)
y += 100;
int radius;
radius = 100;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x, y, radius, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
前两种onPause()
和onResume()
方法是部分Activity
的生命周期,并且当被调用Activity
暂停/恢复。
此图说明了 Android Activity
生命周期。 你可以在这里阅读
它与Activity
的其他onResume
和onPause
方法一起使用的原因是因为您从Activity
的相应方法调用SurfaceView
onPauseMySurfaceView()
和onResumeMySurfaceView()
方法。 如果你不这样做,你的SurfaceView
方法将永远不会被调用,因此永远不会停止/启动线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.