这是我的代码
每次我触摸 imageview 我的应用程序都会等待大约 5 秒然后崩溃
我有互联网权限
在服务器端,我有一个 php 页面,它读取 GET 并将其插入数据库中
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
.
异步任务文档 http://developer.android.com/reference/android/os/AsyncTask.html
这是一个答案 https://stackoverflow.com/questions/15455858/using-asynctask-to-speed-up-android-app-launch-time/15456047#15456047显示了基本结构。基本上,你调用AsyncTask
来自UI
比如在你的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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)