编译并运行但崩溃

时间:2015-06-16 16:21:50

标签: android crash

所以我试图编写代码,每隔5秒就会在屏幕上的随机位置产生一个红色圆圈。我编写的代码只会产生一个红色圆圈,而不是每5秒重复一次,它运行正常。然后,当我添加代码(注释掉)每隔5秒绘制另一个圆圈时,程序仍然编译并运行但在我的测试手机上立即崩溃。这是代码。

public class RandomCircles extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        Timer timer = new Timer();
//       timer.scheduleAtFixedRate(new TimerTask() {
//            public void run() {
                setContentView(new MyView(RandomCircles.this));
//            }
//        }, 0, 5 * 1000L);//5 seconds
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_random_circles, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

class MyView extends View {
    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        //800, 1162
        Random rand = new Random();
        x = rand.nextInt(getWidth());

        if(getWidth() - x < 100)
            x -= 100;
        else if(getWidth() - x > getWidth() - 100)
            x += 100;

        int y = rand.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);
    }
}

这是logcat: enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

通常,涉及用户界面的任何操作都必须在主线程或UI线程中完成,因此,兄弟,您不能在任何其他线程上执行与用户界面相关的任何操作。 您可以通过以下方式使用TimerTask,

Timer timer = new Timer();
timer.scheduleAtFixedRate( new TimerTask() {

        @Override
        public void run() 
        {
            MainActivity.this.runOnUiThread(new Runnable()
            {
                @Override
                public void run() 
                {
                    setContentView(new MyView(MainActivity.this));
                }
            });
        }
      }, 0, 5 * 1000L);

别忘了读这个, Activity.runOnUiThread