这是我的代码 每次我触摸 imageview 我的应用程序等待大约 5 秒然后崩溃
我有上网权限
在服务器端,我有一个读取 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();
}
}
});
}
最佳答案
logcat 会非常有用,但它可能来自于在 UI
上执行网络操作。您应该将所有网络代码移至后台 Thread
,例如 AsyncTask
。这将使您可以轻松地在后台执行网络操作,然后在 UI
上运行的函数中根据需要更新 UI
。
显示基本结构的 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
}
关于android - 每次我发出 http 请求时,应用程序都会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18388468/