【问题标题】:Application doing too much work on main thread应用程序在主线程上做太多工作
【发布时间】:2016-01-13 22:12:29
【问题描述】:

我正在尝试执行下面的方法,但是我不断收到错误消息“跳过 n 帧!应用程序可能在其主线程上做了太多工作。”我试过将 for 和 while 循环分解成这样的线程

 Thread thread = new Thread() {
@Override
public void run() {
    try {
        // for or while loop here
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
};

thread.start();

然而那也根本不起作用。有什么可能的解决办法吗?

public void newSim(int x) {
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    int buttonWidth = (int) (width * 0.15);
    int buttonWidth1 = (int) (width * 0.20);
    int buttonHeight1 = (int) (height * 0.20);

    ArrayList<Point> intersection = new ArrayList<Point>();
    final ArrayList<Point> location = new ArrayList<Point>();

    int constraint = 0;

    int xC = width - buttonWidth1;
    int yC = height - buttonWidth1;

    for (int i = 0; i < x; i++) {
        for (int j = 0; j < x; i++) {
            location.add(new Point(i, j));
            constraint++;
        }
    }

    for (int i = 0; i < x; i++) {
        Random random = new Random();
        Point point = new Point();
        point = location.remove(random.nextInt(constraint));
        while (intersection.contains(point)) {
            intersection.add(point);
            point = location.remove(random.nextInt(constraint));
        }
    Button but1 = new Button(this);
    but1.setText(String.valueOf(i));
    RelativeLayout r = (RelativeLayout) findViewById(R.id.playLayout);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonWidth);
    layoutParams.setMargins(0, 0, buttonWidth, buttonWidth);
    but1.setLayoutParams(layoutParams);
    r.addView(but1);
    constraint--;
    }
}

【问题讨论】:

  • 这是在模拟器还是真机上?
  • 在模拟器上,这可能是原因吗?编辑:实际上我刚刚在手机上尝试过同样的问题
  • 我在 ADB 日志中看到了很多,尤其是在使用模拟器时,我不认为这是一个非常糟糕的问题
  • 你刚刚在手机上试过了,还是不行。

标签: java android multithreading


【解决方案1】:

你在 for 循环中运行了什么?新模拟()?该方法具有 UI 操作。所以它不能在不同的线程中运行。

【讨论】:

  • 是的,我想通了,我没有在 for 循环中运行 newSim,在 onCreate 中调用了 newSim
  • 是的。我不得不写一个答案,因为我无法对原始帖子发表评论。
【解决方案2】:

如果它已经存在于列表中,为什么要添加该点

while (intersection.contains(point)) {
            intersection.add(point);
            point = location.remove(random.nextInt(constraint));
}

你应该使用while(!intersaction.contains())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多