1

这是我每次触摸图像视图时的代码,我的应用程序等待大约 5 秒然后崩溃

我有 INTERNET 权限

在服务器端,我有一个读取 GET 并将其插入数据库的 php 页面

public class Home extends Activity {
ImageView lightbut;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    ImageView lightbut = (ImageView) findViewById(R.id.light);
    lightbut.setClickable(true); 
    lightbut.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("== My activity ===","OnClick is called");
         // Creating HTTP client
            HttpClient httpClient = new DefaultHttpClient();

            // Creating HTTP Post
            HttpGet httpPost = new HttpGet("http://192.168.0.102/HR/index.php?command=ligthsoff");
            try {
                HttpResponse response = httpClient.execute(httpPost);


            } catch (ClientProtocolException e) {
                // writing exception to log
                e.printStackTrace();

            } catch (IOException e) {
                // writing exception to log
                e.printStackTrace();
            }
        }
    });
}
4

1 回答 1

3

logcat 会很有帮助,但它可能来自于在UI. 您应该将所有网络代码移至背景Thread,例如AsyncTask. 这将很容易让您在后台执行网络操作,然后UI根据需要更新在UI.

AsyncTask 文档

这是一个显示基本结构的答案。基本上,您AsyncTaskUI诸如在您的onClick()然后您执行网络操作中doInBackground()调用,当任务首次启动时调用该操作,然后您可以更新它UI的任何其他方法。

使用我引用的示例,您只需将所有网络内容(看起来像您的所有内容)放在链接中示例onClick()的方法中。doInBackground()然后在你的onClick()你会做类似的事情

lightbut.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
       TalkToServer task = new TalkToServer(); // could pass params to constructor here but might not be needed in this situation
       task.execute();  // could pass in params for `doInBackground()` such as url, etc... but again maybe not needed for this situation 
}
于 2013-08-22T18:45:43.300 回答