java回调函数

23 篇文章 0 订阅


package com.example.android_handler_product;

import android.support.v7.app.ActionBarActivity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.android_handler_product.DownLoadImage.ImageCallBack;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 回调函数
 * @author 
 */
public class MainActivity extends ActionBarActivity {

	private ListView listView;
	private ProgressDialog dialog;
	private MyAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) this.findViewById(R.id.listView1);
		adapter = new MyAdapter(MainActivity.this);

		dialog = new ProgressDialog(MainActivity.this);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setTitle("提示");
		dialog.setMessage("正在下载,请稍后....");
		// dialog.setCancelable(false);
		new MyTask().execute(CommonUrl.PRODUCT_URL);
	}

	public class MyTask extends AsyncTask<String, Integer, List<Map<String, Object>>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected List<Map<String, Object>> doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			// 链接网络,获取json数据并进行解析
			// 可以使用json或者gson或者fastjson解析
			InputStream inputStream = null;
			try {
				URL url = new URL(params[0]);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				// connection.setConnectTimeout(3000);
				connection.setRequestMethod("POST");
				connection.setDoInput(true);

				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				if (connection.getResponseCode() == 200) {

					inputStream = connection.getInputStream();
					byte[] data = new byte[1024];
					int len = 0;
					while ((len = inputStream.read(data)) != -1) {
						bos.write(data, 0, len);
					}
					JSONObject jsonObject = new JSONObject(new String(bos.toByteArray()));
					JSONArray jsonArray = jsonObject.getJSONArray("product");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonobj = (JSONObject) jsonArray.get(i);
						Map<String, Object> map = new HashMap<String, Object>();
						Iterator<String> iterator = jsonobj.keys();
						while (iterator.hasNext()) {
							String key = iterator.next();
							map.put(key, jsonobj.get(key));
						}
						list.add(map);
					}
				}
				String str = new String(bos.toByteArray());
				System.out.println("------>>>str:" + str);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (inputStream != null)
					try {
						inputStream.close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
			}
			return list;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			dialog.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(List<Map<String, Object>> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.setData(result);
			listView.setAdapter(adapter);
			adapter.notifyDataSetChanged();
			dialog.dismiss();
		}

	}

	public class MyAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater layoutInflater;
		private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		public MyAdapter(Context context) {
			this.context = context;
			layoutInflater = layoutInflater.from(context);
		}

		public void setData(List<Map<String, Object>> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = null;
			if (convertView == null) {
				view = layoutInflater.inflate(R.layout.item, null);
			} else {
				view = convertView;
			}

			TextView proname = (TextView) view.findViewById(R.id.textView1);
			TextView proaddress = (TextView) view.findViewById(R.id.textView2);
			TextView proprice = (TextView) view.findViewById(R.id.textView3);
			final ImageView proimage = (ImageView) view.findViewById(R.id.imageView1);
			try {
				System.out.println("position:" + position);
				Map<String, Object> map = list.get(position);
				proname.setText(map.get("proname").toString());
				proaddress.setText(map.get("proaddress").toString());
				proprice.setText(map.get("proprice").toString());
				DownLoadImage downLoadImage = new DownLoadImage(
						CommonUrl.PRODUCT_IMAG + "/" + map.get("proimage").toString());
				// 调用回调函数
				downLoadImage.loadImage(new ImageCallBack() {
					@Override
					public void getDrawable(Drawable drawable) {
						// TODO Auto-generated method stub
						proimage.setImageDrawable(drawable);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
			return view;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

package com.example.android_handler_product;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class DownLoadImage {

	private String image_path;

	public DownLoadImage(String image_path) {
		// TODO Auto-generated constructor stub
		this.image_path = image_path;
	}

	public void loadImage(final ImageCallBack callBack) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				callBack.getDrawable((Drawable) msg.obj);
			}
		};

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Drawable drawable = Drawable.createFromStream(new URL(image_path).openStream(), "");
					Message message = Message.obtain();
					message.obj = drawable;
					handler.sendMessage(message);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	// 接口的回调方式
	public interface ImageCallBack {
		public void getDrawable(Drawable drawable);
	}
}




Java中的回调函数是一种常用的编程模式,它允许一个对象在特定事件发生时通知另一个对象。在Java中,回调函数通常通过接口来实现。引用中给出了一个回调函数接口的示例,它定义了一个名为"callback"的方法。 在引用中,类A实现了回调函数接口,该类的方法"a"中创建了一个类B的实例,并将自己作为参数传递给类B的方法"b"。在类B的方法"b"中,它调用了传入的回调函数对象的"callback"方法。这样,在类B中执行特定的逻辑后,会自动调用类A中实现的回调函数方法。通过这种方式,类A可以在类B的特定事件发生时得到通知并执行相应的逻辑。 总结来说,Java中的回调函数是一种通过接口实现的机制,允许一个对象在特定事件发生时通知另一个对象执行相应的逻辑。在类A和类B的示例中,类A实现了回调函数接口,类B在特定时刻调用了类A实现的回调函数方法。这种机制可以实现对象之间的解耦和代码的灵活性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [java中的回调函数](https://blog.csdn.net/hejingfang123/article/details/114040323)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值