-5

我正在开发一个带有 Android 线程的简单应用程序。我的应用程序中有以下代码。但这似乎不起作用。

l = (RelativeLayout)findViewById(R.id.layout_main);
p = new LayoutParams(100, 100);
i = new ImageView(getApplicationContext());
i.setImageResource(R.drawable.bb);
i.setLayoutParams(p);
i.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
    if (running) {
        running = false;
    } else {
        new Thread(new Runnable() {
        @Override
        public void run() {
            while (running) {
                try {
                    Log.d("INFO", "Thread executing");
                    Thread.sleep(100);
                } catch (Exception e) {
                    running = false;
                }
            }
        }
        }).start();
    }

    return false;
}
});
l.addView(i);

甚至日志也没有打印。

编辑:running = false;在代码之前

4

3 回答 3

4

永远不会到达带有日志记录的部分。如果running为真,则设置为假,else不执行分支。如果为假,则永远不会执行循环。

您应该在 else 分支中设置running为。true另请注意,running应该volatile(如果还没有的话)以确保它没有在本地缓存以供 while 循环使用。

于 2013-08-06T11:44:42.137 回答
1

在 android 的主线程上运行线程对如此低内存的性能非常不利

检查这个并行执行工作的异步任务

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }
  }

  public void onClick(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://www.vogella.de" });

  }
于 2013-08-06T12:57:35.950 回答
-1

尝试这个:

i.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Your code here.          
    }
}
于 2013-08-06T11:50:11.440 回答