android之handler 传送非原生类数据

来源:互联网 发布:信达证券软件下载 编辑:程序博客网 时间:2024/06/05 22:43

最近在做一个短信接收程序,用到handler更新ui控件,由于要显示接收到短信的发送者,发送时间,信息内容。常规做法为

Bundle  bundle = new Bundle();

bundle.putString("sender","10010");

bundle.putString("time","201211110001");

bundle.putString("content","hello. i love you");

Message message = new Message();

message.setData(bundle);

handler.sendMessage(message);

//----余下代码省略,

由此引发出一个问题,如果要传递的数据是一个属性众多的复杂类,以上就太繁琐了,且不容易维护。此处仅以上面数据为例,如果将以上信息封装到一个SMS类中,使用更方便。所以你会先定义个SMS类

class SMS

{

  string  sender;

  string time;

  string content;

}

下一个问题又来了,突然发现bundle没有putObject(Object obj)这个函数。

发现他有个putParcelable()方法。

所以你的SMS类需要实现android.os.Parcelable接口.具体做法可以参照网上资料。

在此,我偷了一下懒,有效利用现有资源。直接查找已经实现了Parcelable接口的类,发现了ContentValues类正好适合我的需要。

所以使用它来在逻辑上模拟SMS类

                ContentValues sms=  new ContentValues(20);
                sms.put("sender", senderNum);
                sms.put("time", recTime);
                sms.put("content",content);
                 b.putParcelable("msg", sms);

到此,任务完成。尽量利用已有资源,可以帮你节省很多时间去学该学的东西。


原创粉丝点击