例子:
从服务器获取图片路径,从中取得其中的两条数据,进行下载。
先创建一个实体类,保存图片的数据:
public class PictureSet {
public int cameraId;
public String pictureName;
public String pictureData;
public String createTime;
public PictureSet(int cameraId1,String pictureName1,String pictureData1,String createTime1){
this.cameraId = cameraId1;
this.pictureName = pictureName1;
this.pictureData = pictureData1;
this.createTime = createTime1;
}
public PictureSet(){
}
}
页面:
public class ImgDownActivity extends Activity implements View.OnClickListener {
private TextView tv_path1,tv_path2;
private Button btn_obtain,btn_downImg1,btn_downImg2;
private ImageView iv_img1,iv_img2;
private String netImgStr;
private String retCode,retInfo;
private Bitmap bm1,bm2;
private ProgressDialog mDialog;
private String passMsg1,passMsg2;
//下载路径
private final static String reqeustURL = "http://103.8.220.166:40000/lechu/device/image/filedownload";
//保存路径页面布局:
private final static String ALBUM_PATH = Environment.getExternalStorageDirectory()+"/download_test/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fild_down_load);
//获取网络图片信息
btn_obtain = (Button)findViewById(R.id.btn_obtain);
btn_obtain.setOnClickListener(this);
tv_path1 = (TextView)findViewById(R.id.tv_imgPath1);
tv_path2 = (TextView)findViewById(R.id.tv_imgPath2);
iv_img1 = (ImageView)findViewById(R.id.iv_img1);
iv_img2 = (ImageView)findViewById(R.id.iv_img2);
btn_downImg1 = (Button)findViewById(R.id.btn_down1);
btn_downImg2 = (Button)findViewById(R.id.btn_down2);
btn_downImg1.setOnClickListener(this);
btn_downImg2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_obtain:
final ObtainHandler obtainHandler = new ObtainHandler();
new Thread(){
public void run(){
Looper.prepare();
ImgDownUtil imgDownUtil = new ImgDownUtil();
//netImgStr = getImgFromServer(getLocalMac());
netImgStr = imgDownUtil.getImgFromServer(getLocalMac());
Log.i("inputstream",netImgStr);
//Bundle mBundle = getBundleFromStr(netImgStr);
Bundle mBundle = imgDownUtil.getBundleFromStr(netImgStr);
//获取图片信息,并将其转换成byte[]
List<PictureSet> imgList = (ArrayList)(mBundle.getStringArrayList("retResult"));
byte[] data = null;
List<byte[]> byteList = new ArrayList<byte[]>();
for(int j=0;j<imgList.size();j++){
data = imgDownUtil.getImg(imgList.get(j).pictureData);
byteList.add(data);
mBundle.putByteArray("imgPath" + j, data);
}
Message msg = new Message();
msg.setData(mBundle);
obtainHandler.sendMessage(msg);
}
}.start();
break;
case R.id.btn_down1:
mDialog = ProgressDialog.show(ImgDownActivity.this,"保存图片","图片正在保存,请稍候……",true);
final SaveImgHandler saveImgHandler = new SaveImgHandler();
new Thread(){
public void run(){
Looper.prepare();
ImgDownUtil imgDownUtil = new ImgDownUtil();
try{
imgDownUtil.saveFile(bm1, "bm1.jpg");
passMsg1 = "图片保存成功!";
}catch (Exception ex){
ex.printStackTrace();
passMsg1 = "图片保存失败!";
}
saveImgHandler.sendMessage(saveImgHandler.obtainMessage());
}
}.start();
break;
case R.id.btn_down2:
mDialog = ProgressDialog.show(ImgDownActivity.this,"图片保存","图片正在保存,请稍候……",true);
final SaveImgHandler saveImgHandler1 = new SaveImgHandler();
new Thread(){
public void run(){
Looper.prepare();
try{
ImgDownUtil imgDownUtil = new ImgDownUtil();
imgDownUtil.saveFile(bm2,"bm2.jpg");
passMsg1 = "图片保存成功!";
}catch (Exception ex){
ex.printStackTrace();
passMsg1 = "图片保存失败!";
}
saveImgHandler1.sendMessage(saveImgHandler1.obtainMessage());
}
}.start();
break;
}
}
//获取图片信息,并显示在页面上
class ObtainHandler extends Handler{
public ObtainHandler(){
}
public ObtainHandler(Looper l){
super(l);
}
//更新UI
public void handleMessage(Message msg){
Bundle bakBundle = msg.getData();
retCode = bakBundle.getString("retCode");
List<PictureSet> list = (ArrayList)(bakBundle.getStringArrayList("retResult"));
if(retCode.equals("00000")){
Toast.makeText(ImgDownActivity.this,bakBundle.getString("retInfo"),Toast.LENGTH_SHORT).show();
//显示网络图片的路径
tv_path1.setText(list.get(0).pictureData);
tv_path2.setText(list.get(1).pictureData);
//显示图片
byte[] imgByte1 = bakBundle.getByteArray("imgPath1");
bm1 = BitmapFactory.decodeByteArray(imgByte1,0,imgByte1.length);
Log.i("bm1Info",bm1.getConfig().toString());
iv_img1.setImageBitmap(bm1);
byte[] imgByte2 = bakBundle.getByteArray("imgPath2");
bm2 = BitmapFactory.decodeByteArray(imgByte2,0,imgByte2.length);
iv_img2.setImageBitmap(bm2);
}
}
}
//图片保存成功后关闭等待对话框,并弹出页面提示
class SaveImgHandler extends Handler{
public SaveImgHandler(){
}
public SaveImgHandler(Looper l){
super(l);
}
public void handleMessage(Message msg){
mDialog.dismiss();
Toast.makeText(ImgDownActivity.this,passMsg1,Toast.LENGTH_SHORT).show();
}
}
//获取设备的MAC地址
public String getLocalMac(){
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String macStr = info.getMacAddress();
//将MAC地址转换成小写不带:的形式
String[] macAddr = macStr.toLowerCase().split(":");
String mac1="";
for(int i=0;i<macAddr.length;i++){
mac1 = mac1+macAddr[i];
}
return mac1;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"从服务器获取数据,在页面上显示图片,并保存到本地的方法:
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="图片1:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_imgPath1"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_down1"
android:text="下载"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="图片2:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_imgPath2"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_down2"
android:text="下载"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btn_obtain"
android:text="获取图片信息"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
public class ImgDownUtil {
private final static String reqeustURL = "http://103.8.220.166:40000/lechu/device/image/filedownload";
private final static String ALBUM_PATH = Environment.getExternalStorageDirectory()+"/download_test/";
private Bundle bundle;
public ImgDownUtil(){
}
//从服务器上获取响应数据
public String getImgFromServer(String mac){
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(reqeustURL+"/"+mac+"/");
String imgStream = null;
try{
HttpResponse hresponse = client.execute(httpGet);
HttpEntity entity = hresponse.getEntity();
imgStream = EntityUtils.toString(entity);
// is = entity.getContent();
}catch (Exception ex){
ex.printStackTrace();
}
return imgStream;
}
//将从服务器上获取的字符串转化成Bundle
public Bundle getBundleFromStr(String str){
try{
JSONObject jsonObject = new JSONObject(str);
bundle = new Bundle();
bundle.putString("retCode",jsonObject.getString("retCode").toString());
bundle.putString("retInfo",jsonObject.getString("retInfo").toString());
//JSONObject subObject = new JSONObject(jsonObject.getString("retResult"));
String jsonStr = jsonObject.getString("retResult");
// String str = jsonStr.substring(1).replace("]", "");
JSONArray jsonArr = new JSONArray(jsonStr);
List<PictureSet> psList = new ArrayList<PictureSet>();
for(int i=0;i<jsonArr.length();i++){
JSONObject subObject = new JSONObject(jsonArr.get(i).toString());
PictureSet ps = new PictureSet();
ps.cameraId = subObject.getInt("cameraId");
ps.pictureName = subObject.getString("pictureName");
ps.createTime = subObject.getString("createTime");
ps.pictureData = subObject.getString("pictureData");
psList.add(ps);
Log.i("subObject", jsonArr.get(i).toString());
}
bundle.putStringArrayList("retResult", (ArrayList) psList);
}catch (Exception ex){
ex.printStackTrace();
}
return bundle;
}
//获取图片
public byte[] getImg(String imgPath){
try{
URL url = new URL(imgPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
InputStream is = conn.getInputStream();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return readStream(is);
}
}catch (MalformedURLException mue){
//URL抛出的异常
mue.printStackTrace();
}catch (IOException ie){
//HttpURLConnection抛出的异常。
ie.printStackTrace();
}
return null;
}
//将图片流转化为数据
public static byte[] readStream(InputStream inputStream){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len =0;
try{
while ((len = inputStream.read(buffer))!=-1){
byteArrayOutputStream.write(buffer,0,len);
}
byteArrayOutputStream.close();
inputStream.close();
}catch (Exception ex){
ex.printStackTrace();
}
return byteArrayOutputStream.toByteArray();
}
//保存图片到本地
public void saveFile(Bitmap bm,String imgName){
File dirFile = new File(ALBUM_PATH);
if(!dirFile.exists()){
dirFile.mkdir();
}
File myFile = new File(ALBUM_PATH+imgName);
try{
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myFile));
bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
bos.flush();
bos.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。