anroid 學習之java回調機制與自定義接口回調方法的使用

android中經常會用到內部類方式的監聽接口,如按鈕中的onClickListener等,內部類接口中會用到回調方法;同時在多線程操作中,子線程進行耗時操作時,如向服務器發送請求,服務器的數據響應是無法進行的,這時候需要利用java的回調機制解決問題。通過重寫回調方法獲取請求結果

這裏以網絡下載爲例,封裝一個網絡下載類,並且實現自定義接口回調方法;


先建立一個接口:

package com.example.menu;

public interface HttpCallbackListener {
	void onFinish(String response);
	void onError(Exception e);
}


建立封裝的網絡操作工具類

package com.example.menu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.example.menu.HttpCallbackListener;
public class HttpUtil {

	public  static void sendHttpRequest(final String address,final HttpCallbackListener listner){
		
		new Thread(new Runnable(){
				public void run() {
					HttpURLConnection connection=null;
					try {
						URL url =new URL(address);
					
						connection =(HttpURLConnection) url.openConnection();
						connection.setRequestMethod("GET");
						connection.setConnectTimeout(8000);
						connection.setReadTimeout(8000);
						connection.setDoInput(true);
						connection.setDoOutput(true);
						InputStream in =connection.getInputStream();
						BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
						StringBuilder response= new StringBuilder();
						String line;
						
						while((line=reader.readLine())!=null){
							response.append(line);
						}
						if(listner!=null){
							listner.onFinish(response.toString());
						}
					} catch (Exception e) {
						if(listner!=null){
							listner.onError(e);
						}
					}finally{
						if(connection!=null){
							connection.disconnect();
						}
					}
				}
			}
		).start();
	}
}




在mainActivity活動中使用工具類


protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		
		
		final Handler handler =new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		if(msg.what==1){
        			String  info =(String) msg.obj;
        			Toast.makeText(getApplicationContext(), ""+info, Toast.LENGTH_SHORT).show();
        		}
        	}
        };
        
		 HttpUtil.sendHttpRequest("http://www.baidu.com",new HttpCallbackListener(){
			
			 public void onFinish(String response) {
				 System.out.println(response);
					Message msg =handler.obtainMessage();
					msg.what=1;
					msg.obj=response;
					handler.sendMessage(msg);
			  };
			  
			  public void onError(Exception e) { 
				  System.out.println("系統出錯:"+e.toString());
			  };
		  });
		
	}


上面代碼中通過HttpUtils工具類的sendHttpRequest()方法,傳遞一個網址參數,通過子線程操作執行數據下載,然後通過重寫接口實例,重寫接口方法,獲取了之前操作的結果;然後將結果通過Handler發送消息,當handler觸發handMessage回到方法的時候,就可以獲取最終的效果!整個過程用到了接口回調機制和之前常用的監聽器效果大同小異,非常有助於理解android的事件回調機制和匿名內部類的使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章