Wireless Messaging API (JSR-120 or WMA) 允許訪問J2ME設備上的無線通訊資源來發送文本、二進制和MultiPart消息,MMS 屬於MultiPart消息.
下邊的例子代碼說明了如何在J2ME程序裡發送和接收MMS
public void sendMMS()
{
String appID = getAppProperty("MMS-ApplicationID");
String address = "mms://+5550000:" + appID;
MessageConnection mmsconn = null;
try
{
/** 打開連接 */
mmsconn = (MessageConnection) Connector.open(address);
MultipartMessage mmmessage =(MultipartMessage) mmsconn.newMessage(
MessageConnection.MULTIPART_MESSAGE);
mmmessage.setAddress(address);
MessagePart[] parts = getParts();
for (int i = 0; i < parts.length; i++)
{
mmmessage.addMessagePart(parts[i]);
}
mmmessage.setSubject("MMS Text");
mmsconn.send(mmmessage);
}
catch (Exception e) {
}
if (mmsconn != null)
{
try
{
mmsconn.close();
}
catch (IOException ioe) {
}
}
}
public MessagePart[] getParts()
{
// parts 是一個Vector對象,它包括Mulitpart 消息
MessagePart[] partsArray = new MessagePart[parts.size()];
parts.copyInto(partsArray);
return partsArray;
}
public void addPart()
{
Vector parts = new Vector();
int counter = 0;
MessagePart mpart;
/*這裡添加文本*/
String mimeType = "text/plain";
String encoding = "UTF-8";
String text = "Hello";
byte[] contents = text.getBytes(encoding);
mpart = new MessagePart(contents, 0, contents.length, mimeType, "id" +
counter, "contentLocation", encoding);
counter ++;
/*這裡添加圖像*/
String mimeType = "image/png";
String image = "/hello.png";
InputStream is = getClass().getResourceAsStream(image);
byte[] contents = new byte[is.available()];
is.read(contents);
mpart = new MessagePart(contents, 0, contents.length,mimeType, "id" +
counter,"contentLocation", null);
parts.addElement(mpart);
counter ++;
}
public void run()
{
String mmsConnection = "mms://:" + appID;
try
{
mmsconn = (MessageConnection) Connector.open(mmsConnection);
mmsconn.setMessageListener(this);
}
catch (IOException ioe) {
}
try
{
Message msg = mmsconn.receive();
if (msg != null)
{
String senderAddress = msg.getAddress();
String title = senderAddress.substring(6);
if (msg instanceof MultipartMessage)
{
MultipartMessage mpm = (MultipartMessage)msg;
String subject = mpm.getSubject();
String date = mpm.getTimestamp().toString();
MessagePart[] parts = mpm.getMessageParts();
if (parts != null)
{
for (int i = 0; i < parts.length; i++)
{
MessagePart mp = parts[i];
String mimeType = mp.getMIMEType();
String contentLocation = mp.getContentLocation();
byte[] ba = mp.getContent();
try
{
Image image = Image.createImage(ba, 0, ba.length);
}
catch (IllegalArgumentException iae)
{}
}
}
}
}
}
catch (IOException e) {
}
}