【问题标题】:App crashes every time i make an http request每次我发出 http 请求时应用程序都会崩溃
【发布时间】:2013-08-22 18:43:43
【问题描述】:

这是我的代码 每次我触摸图像视图时,我的应用都会等待大约 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();
            }
        }
    });
}

【问题讨论】:

标签: android http crash request


【解决方案1】:

logcat 会很有帮助,但它可能来自于在UI 上做网络工作。您应该将所有网络代码移动到背景Thread,例如AsyncTask。这将很容易让您在后台执行网络操作,然后在 UI 上运行的函数中根据需要更新 UI

AsyncTask Docs

Here is an answer 显示基本结构。基本上,您从UI 中调用AsyncTask,例如在您的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 
}

【讨论】:

  • 我该怎么做?如果你给我一个代码,我将非常感激!
  • 我已经编辑了一个开始使用它的示例的链接。您还应该阅读文档,因为您需要了解重要信息。
  • 我再次编辑了一些描述。这应该让你开始。如果在其他任何地方都不需要它,您可以简单地将 AsyncTask 设为您的 Activity 的内部类。然后你可以访问Activity的成员变量以及访问它的函数
猜你喜欢
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多