android 代码片段,android 中常用代码片段 -尊龙游戏旗舰厅官网
一:asynctask 的使用
(1)activity_main.xml
(2)mainactivity.java
public class mainactivity extends activity {
private progressbar asyncpb = null;
private textview tvinfo = null;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
tvinfo = (textview)findviewbyid(r.id.tvinfo);
string params = "welcome to here";
new myasynctask().execute(params);
}
private class myasynctask extends asynctask{
@override
protected void onpreexecute() {
//做一些预处理
asyncpb = (progressbar)findviewbyid(r.id.asyncpb);
asyncpb.setvisibility(view.visible);
}
@override
protected string doinbackground(string... params) {
//执行耗时操作,网络任务、文件操作、数据库操作、复杂计算操作
int myprogress = 0;
int length = params[0].length();
for(int i=1; i<=length; i ){
myprogress = i;
//模拟耗时操作
try {
thread.sleep(300);
} catch (interruptedexception e) {
e.printstacktrace();
}
publishprogress((int)((myprogress/(float)length)*100));
}
//它将传递给onpostexecute
return params[0];
}
@override
protected void onprogressupdate(integer... values) {
//更新进度条
asyncpb.setprogress(values[0]);
tvinfo.settext("已加载:" (values[0]) "%");
}
@override
protected void onpostexecute(string result) {
//更新ui
tvinfo.settext("加载完成:" result);
}
}
}
二:httpget
public static string getrequest(string url){
string result = "";
httpclient client = new defaulthttpclient();
httpget get = new httpget(url);
try {
httpparams httpparams = client.getparams();
httpconnectionparams.setconnectiontimeout(httpparams, 3000);
httpconnectionparams.setsotimeout(httpparams, 5000);
httpresponse response = client.execute(get);
if(response.getstatusline().getstatuscode() == httpstatus.sc_ok){
result = entityutils.tostring(response.getentity()).trim();
}
} catch (exception e) {
//连接超时
}
return result;
}
三:volley post
private requestqueue rqueue = null;
rqueue=wzhvolley.getrequestqueue();
stringrequest postrequest= newstringrequest(
request.method.post,
url,
createdosuccess(),
createdoerror()){protected mapgetparams(){
map params = new hashmap();
params.put(key,value);returnparams;
}
};
postrequest.setretrypolicy(newdefaultretrypolicy(wr.default_timeout_ms, wr.default_max_retries, wr.default_backoff_mult));
rqueue.add(postrequest);private response.listenercreatedosuccess(){return new response.listener(){public voidonresponse(string arg0){//...
jsonobject jsonobj = newjsonobject(arg0);//or
jsonarray jsonarr = newjsonarray(arg0);
}
};
}privateresponse.errorlistener createdoerror(){return newresponse.errorlistener(){public voidonerrorresponse(volleyerror arg0){//...
}
};
}
总结
以上是尊龙游戏旗舰厅官网为你收集整理的android 代码片段,android 中常用代码片段的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 如何对android菜单,android
- 下一篇: