Android传递Bitmap对象在两个Activity之间

时间:2022-06-08 21:57:32

通过内部存储方式实现了在两个activity之间传递bitmap对象以及其它支持串行化的java对象,关键点有如下:

1.  http客户端下载图片,通过imageview对象显示

2.  把imageview上的bitmap对象从当前activity传递到另外一个activity中并显示出来

3.  基于串行化传递java对象数据

首先看我是怎么实现http客户端下载图片,通过异步task接口实现http客户端下载图片并通过handler来更新imageview,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.example.sharedemo;
 
import java.io.ioexception;
import java.io.inputstream;
 
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.client.clientprotocolexception;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.defaulthttpclient;
 
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.os.asynctask;
import android.os.handler;
import android.os.message;
import android.util.log;
 
public class imageloadtask extends asynctask<string, void, bitmap> {
  private handler handler;
 
  public imageloadtask(handler handler) {
    this.handler = handler;
  }
 
  protected void onpostexecute(bitmap bitmap) {
    message msg = new message();
    msg.obj = bitmap;
    handler.sendmessage(msg);
  }
 
  @override
  protected bitmap doinbackground(string... urls) {
    bitmap bitmap = null;
    // create http client
    httpclient httpclient = new defaulthttpclient();
    try {
      // get request
      log.i("image-url", urls[0]);
      httpget httprequest = new httpget(urls[0]);
      httpresponse httpresponse = httpclient.execute(httprequest);
      if (httpresponse.getstatusline().getstatuscode() == httpstatus.sc_ok) {
        // get entity from response
        httpentity httpentity = httpresponse.getentity();
        // read stream
        inputstream is = httpentity.getcontent();
        bitmap = bitmapfactory.decodestream(is);
        is.close();
        log.i("image", "already get the image by url : " + urls[0]);
      }
 
    } catch (clientprotocolexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      httpclient.getconnectionmanager().shutdown();
    }
    return bitmap;
  }
 
}

在当前的activity中通过按钮上的事件响应实现切换view到对应的activity中去,同时实现java串行化数据传递。mainactivity的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.example.sharedemo;
 
import java.io.bytearrayoutputstream;
import java.io.fileoutputstream;
 
import android.app.activity;
import android.content.context;
import android.content.intent;
import android.graphics.bitmap;
import android.graphics.matrix;
import android.graphics.drawable.bitmapdrawable;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.imageview;
 
public class mainactivity extends activity implements onclicklistener{
  public final static string share_bitmap_command = "share-image";
  public final static string share_text_data_command = "share-text-data";
  private handler handler;
 
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    setuponclicklistener();
  }
 
  private void setuponclicklistener() {
    button bitmapbtn = (button)this.findviewbyid(r.id.bitmapsharebtn);
    bitmapbtn.settag(share_bitmap_command);
    bitmapbtn.setonclicklistener(this);
    button textdatabtn = (button)this.findviewbyid(r.id.mapsharebtn);
    textdatabtn.settag(share_text_data_command);
    textdatabtn.setonclicklistener(this);
    final imageview imageview = (imageview)this.findviewbyid(r.id.imageview1);
     
    handler = new handler()
    {
      public void handlemessage(message msg) {
        bitmap bitmap = (bitmap)msg.obj;
        if(bitmap != null)
        {
          /*
          // 为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始bitmap占用的内存
          bitmap smallbitmap = zoombitmap(bitmap, bitmap.getwidth()/ 5, bitmap.getheight() / 5);
          // 释放资源
          bitmap.recycle();
          // 显示图片
          imageview.setimagebitmap(smallbitmap);
          imageview.invalidate();
          */
          imageview.setimagebitmap(bitmap);
        }
      }
    };
    imageloadtask task = new imageloadtask(handler);
    task.execute("http://img.blog.csdn.net/20150607143208238");
  }
   
  public static bitmap zoombitmap(bitmap bitmap, int width, int height) {
    int w = bitmap.getwidth();
    int h = bitmap.getheight();
    matrix matrix = new matrix();
    float scalewidth = ((float) width / w);
    float scaleheight = ((float) height / h);
    matrix.postscale(scalewidth, scaleheight); // 不改变原来图像大小
    bitmap newbmp = bitmap.createbitmap(bitmap, 0, 0, w, h, matrix, true);
    return newbmp;
  }
 
  @override
  public void onclick(view v) {
    object tag = v.gettag();
    log.i("command", tag.tostring());
    if(share_bitmap_command.equals(tag))
    {
      intent intent = new intent(this.getapplicationcontext(), imageprocessactivity.class);
      imageview imageview = (imageview)this.findviewbyid(r.id.imageview1);
      bitmap bitmap = ((bitmapdrawable)imageview.getdrawable()).getbitmap();
      intent.putextra("selectedimage", bitmap);
      intent.putextra("name", "lena");
      intent.putextra("description", "超级大美女");
      this.startactivity(intent);     
    }
    else if(share_text_data_command.equals(tag))
    {
      intent intent = new intent(this.getapplicationcontext(), imageprocessactivity.class);
      imageview imageview = (imageview)this.findviewbyid(r.id.imageview1);
      bitmap bitmap = ((bitmapdrawable)imageview.getdrawable()).getbitmap();
      // save it first then pass uri
      imageinfobean dto = new imageinfobean();
      string uri = createimagefrombitmap(bitmap);
      dto.setdescription("超级大美女");
      dto.setname("lena");
      dto.seturi(uri);
       
      intent.putextra("tiger", dto);
      this.startactivity(intent); 
    }
  }
   
  public string createimagefrombitmap(bitmap bitmap) {
    string filename = "myimage";
    try {
      bytearrayoutputstream bytes = new bytearrayoutputstream();
      bitmap.compress(bitmap.compressformat.jpeg, 100, bytes);
      fileoutputstream fo = openfileoutput(filename, context.mode_private);
      fo.write(bytes.tobytearray());
      fo.close();
    } catch (exception e) {
      e.printstacktrace();
      filename = null;
    }
    log.i("filename", filename);
    return filename;
  }
}

对应另外一个activity中实现读取与组装bitmap对象显示的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.example.sharedemo;
 
import java.io.filenotfoundexception;
 
import android.app.activity;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.os.bundle;
import android.widget.imageview;
import android.widget.textview;
 
public class imageprocessactivity extends activity {
 
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.share_info);
    backfilldata();
  }
 
  private void backfilldata() {
    object obj = this.getintent().getextras().get("tiger");
    imageview imageview = (imageview)this.findviewbyid(r.id.imageview1);
    textview text1 = (textview)this.findviewbyid(r.id.textview1);
    textview text2 = (textview)this.findviewbyid(r.id.textview2);
    try {
      if(obj != null && obj instanceof imageinfobean)
      {
        imageinfobean dto = (imageinfobean)obj;
        bitmap bitmap = bitmapfactory.decodestream(this.openfileinput(dto.geturi()));
        imageview.setimagebitmap(bitmap);
        imageview.invalidate(); // refresh
         
        text1.settext("名称: " + dto.getname());
        text2.settext("描述: " + dto.getdescription());
        return;
      }
    } catch (filenotfoundexception e) {
      e.printstacktrace();
    }
     
    bitmap bitmap = (bitmap) this.getintent().getparcelableextra("selectedimage");
    string name = this.getintent().getextras().getstring("name");
    string description = this.getintent().getextras().getstring("description");
    if(bitmap != null)
    {
      imageview.setimagebitmap(bitmap);
      imageview.invalidate(); // refresh
    }
    if(name != null)
    {
      text1.settext("名称: " + name);
    }
    if(description != null)
    {
      text2.settext("描述: " + description);
    }
  }
 
}

对应的java串行化对象类代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.example.sharedemo;
 
import java.io.serializable;
 
public class imageinfobean implements serializable {
  /**
   *
   */
  private static final long serialversionuid = 1l;
 
  public string getname() {
    return name;
  }
 
  public void setname(string name) {
    this.name = name;
  }
 
  public string getdescription() {
    return description;
  }
 
  public void setdescription(string description) {
    this.description = description;
  }
 
  public string geturi() {
    return uri;
  }
 
  public void seturi(string uri) {
    this.uri = uri;
  }
 
  private string name;
  private string description;
  private string uri;
 
}

最后声明:
别忘记在manifest文件添加网络访问的权限

?
1
<uses-permission android:name="android.permission.internet"/>

Android传递Bitmap对象在两个Activity之间

第一个按钮【传递图片】将会演示我遇到错误,第二按钮【传递文本数据】
将会演示正确的处理结果,显示如下:

Android传递Bitmap对象在两个Activity之间

以上就是本文的全部内容,希望对大家的学习有所帮助。