Android 中常用代码片段

一:AsyncTask 的使用

(1)activity_main.xml

<TextView

        android:id="@+id/tvInfo"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />

    

<ProgressBar   

         android:layout_below="@id/tvInfo"

         android:id="@+id/asyncPb"    

         style="?android:attr/progressBarStyleHorizontal" 

         android:layout_width="fill_parent"   

         android:layout_height="wrap_content"  

         android:visibility="gone" />

(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<String, Integer, String>{

		@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 = new StringRequest(

    Request.Method.POST,

    URL,

    createDoSuccess(),

    createDoError()){

        protected Map<String,String> getParams(){

            Map<String,String> params = new HashMap<String,String>();

            params.put(key,value);

            return params;

        }

    };

    

postRequest.setRetryPolicy(new 

    DefaultRetryPolicy(WR.DEFAULT_TIMEOUT_MS, WR.DEFAULT_MAX_RETRIES, WR.DEFAULT_BACKOFF_MULT));

rQueue.add(postRequest);



private Response.Listener<String> createDoSuccess(){

    return new Response.Listener<String>(){

        public void onResponse(String arg0){

            //...

            JSONObject jsonObj = new JSONObject(arg0);

            //or

            JSONArray jsonArr = new JSONArray(arg0);

        }

    };

}

private Response.ErrorListener createDoError(){

    return new Response.ErrorListener(){

        public void onErrorResponse(VolleyError arg0){

            //...

        }

    };

}

 

你可能感兴趣的:(android)