如何javame调用goo.gl短网址服务

直接上代码:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import org.json.me.JSONObject;

public class GooglUtils {
private static String GOOGL_API_ENDPOINT=”http://goo.gl/api/shorten?security_token=null&url=”;
public static String shorten(String url) throws Exception{
HttpConnection con = null;
InputStream in = null;
OutputStream out = null;
ByteArrayOutputStream bos = null;
OutputStreamWriter osw = null;
InputStreamReader isr = null;
byte[] request;
int messageLength;

try {
bos = new ByteArrayOutputStream();
osw = new OutputStreamWriter(bos, “UTF-8”);
//            osw.write(url);
osw.flush();

request = bos.toByteArray();
messageLength = request.length;

con = (HttpConnection) Connector.open(GOOGL_API_ENDPOINT+url, Connector.READ_WRITE);
con.setRequestMethod(HttpConnection.POST);
con.setRequestProperty(“Content-Length”, Integer
.toString(messageLength));
con.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded;charset=utf-8″);
out = con.openOutputStream();
out.write(request);
in = con.openInputStream();
isr = new InputStreamReader(in,”UTF-8”);

char[] buf = new char[256];
int rsize = 0;
StringBuffer sb = new StringBuffer();
while((rsize=isr.read(buf))>0){
sb.append(buf,0,rsize);
}
System.out.println(sb.toString());

JSONObject jo = new JSONObject(sb.toString());
String shorturl = (String) jo.get(“short_url”);
System.out.println(shorturl);
return shorturl;

} catch (Exception x) {
throw x;
} finally {
try {
if (con != null)
con.close();
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}

how big should the byte array be in java me(j2me)

Keep getting the out of memory error when handling the image file in emulator(wtk) and device(e61i)
Just had a simple test and here is what I found:
The code is simple:
for(int i=1000;i<Integer.MAX_VALUE;i++){
System.out.println(i);
byte[] buf = new byte[i];
}
and see when your program will crash. – Actually it won’t crash, as the OOME(out of memory error), is an Error rather RuntimeException, when the OOME is thrown, the program just go on.

Let’s see the result:
In wtk2.5.2 emulator: the size cannot beyond “2003765” byte(for comparison: we can reserve byte array of size  Integer.MAX_INTEGER/40 – 53687091 in standard version on my laptop).
In e61i: not instrumented yet. My guess is maybe much smaller, as I had experience that OOME thrown when the image size is only 300k, what different is: the byte array CAN take up to that size, however error happened when handling the image(when trying to createImage from byte array).
I followed this thread and the guys found that 400k bytes is the limit on nokia6681.

Another depressing result.

S60里的系统属性

http://www.forum.nokia.com/document/Java_ME_Developers_Library_v1/index.html?content=GUID-545CA84A-8378-4DFA-9035-94479F5BE26E.html

一些常用的路径,比如图像路径,存储卡路径,相机路径

 System properties

The table below contains the File API system properties that return the localized names of common directories and the URLs to the most common directories. Several Strings are only supported in either S60 or Series 40. Refer to the individual tables for each implementation.

String Description
Fileconn.dir.photos.name Localized name for the photo directory, for example “Images“.
Fileconn.dir.graphics.name Localized name for the graphic directory, for example “Graphic clips“.
Fileconn.dir.music.name Localized name for the music directory, for example “Music clips“.
Fileconn.dir.memorycard.name Localized UI name for the memory card of directory, for example “Memory card“.
Fileconn.dir.photos The URL of the default storage directory for photos captured with the integrated camera and other images. For example, “file:///c:/My files/Images/“.
Fileconn.dir.graphics The URL of the default storage directory for clip art graphics (caller group icons, background pictures, and other similar items). For example, “file:///c:/My files/Graphic clips/“.
Fileconn.dir.music The URL of the default storage directory for music files (MP3, AAC, and others). For example, “file:///c:/My files/Music clips/“.
Fileconn.dir.memorycard Root directory of memory card. For example, “file:///e:/“.

Example for S60:

String url = System.getProperty("fileconn.dir.photos") + "myImage.jpg";

The Content of the URL is file:///c:/data/Images/myImage.jpg

String Description
Fileconn.dir.photos.name Localized name for the photo directory, for example “Images“.
Fileconn.dir.graphics.name Localized name for the graphic directory, for example “Graphic clips“.
Fileconn.dir.music.name Localized name for the music directory, for example “Music clips“.
Fileconn.dir.memorycard.name Localized UI name for the memory card of directory, for example “Memory card“.
Fileconn.dir.photos The URL of the default storage directory for photos captured with the integrated camera and other images. “file:///C:/predefgallery/predefphotos“.
Fileconn.dir.graphics The URL of the default storage directory for clip art graphics (caller group icons, background pictures, and other similar items). “file:///C:/predefgallery/predefgraphics“.
Fileconn.dir.music The URL of the default storage directory for music files (MP3, AAC, and others). “file:///C:/predefgallery/predefmusic“.
Fileconn.dir.themes The URL of the default storage directory for themes. “file:///C:/predefgallery/predefthemes

Example for Series 40:

String url = System.getProperty("fileconn.dir.photos") + "myImage.jpg";

The Content of the URL is file:///C:/predefgallery/predefphotos/myimage.jpg

Javablog » How MIDlet Signing is Killing J2ME

Javablog » How MIDlet Signing is Killing J2ME

TODO: 翻译

让VideoControl支持更高的分辨率

如果直接videoControl.getSnapshot(null)的话,得到的是默认的较低分辨率和画质-在我的e61i上是640*480,这样显然不能充分利用2M像素的相机。(当然也要看了,你指望从手机上传出多清晰的照片,而且也要有兼容的问题,万一其他手机支持不到这么高怎么办?)通过设置width和height即可以支持更高的分辨率。

videoControl.setVisible(false);
String enc = “encoding=jpeg&width=800&height=600“;
byte[] raw = videoControl.getSnapshot(enc);
appendImage(raw);
在我的小6上测试:
1600*1200 – 无法处理的异常(应该是得到的byte[]太大,ME的Vector会溢出),1200*900 – MediaException : Symbian OS Error: -4,貌似不支持这个分辨率
1280*960 – 同上
1024*768 – 同上
800*600 –  成功
640*480 – 成功,默认的分辨率

参考:nokia.wiki


Powered by MoFire

转贴一些关于MMAPI的样例代码

本文的目的是为读者提供处理不同情况的代码,您可以参考MMAPI DOC。

播放单音

try
{
Manager.playTone(ToneControl.C4, 5000
/* millisec */, 100 /* max vol */);
} catch (MediaException e)
{
}

简单媒体重放功能实现:

try
{
Player p = Manager.createPlayer
(“http://webserver/music.mp3”);
p.setLoopCount(5);
p.start();
} catch (IOException ioe)
{
} catch (MediaException me)
{
}

详细重放控制:

static final long SECS_TO_MICROSECS
= 1000000L;
Player p;
VolumeControl vc;
try {
p = Manager.createPlayer
(“http://webserver/music.mp3”);
p.realize();
// Set a listener.
p.addPlayerListener(new Listener());
// Grab volume control for the player.
// Set Volume to max.
vc = (VolumeControl)p.getControl
(“VolumeControl”);
if (vc != null)
vc.setLevel(100);
// Set a start time.
p.setMediaTime(5 * SECS_TO_MICROSECS);
// Guarantee that the player
can start with the smallest latency.
p.prefetch();
// Non-blocking start
p.start();
} catch (IOException ioe)
{
} catch (MediaException me)
{
}
class Listener implements PlayerListener
{
public void playerUpdate(Player p,
String event, Object eventData)
{
if (event == END_OF_MEDIA
|| event == STOP_AT_TIME)
{
System.out.println
(“Done processing”);
try {
p.setMediaTime
(5 * SECS_TO_MICROSECS);
p.start();
} catch (MediaException me)
{
}
break;
}
}
}

实现MIDI重放控制:

Player p;
TempoControl tc;

try {
p = Manager.createPlayer
(“http://webserver/tune.mid”);
p.realize();

// Grab the tempo control.
tc = (TempoControl)p.getControl
(“TempoControl”);
tc.setTempo(120000);
// 120 beats/min
p.start();

} catch (IOException ioe)
{
} catch (MediaException me)
{
}

视频重放功能实现:

Player p;
VideoControl vc;

try {
p = Manager.createPlayer
(“http://webserver/movie.mpg”);
p.realize();

// Grab the video control
and set it to the current display.
vc = (VideoControl)p.getControl
(“VideoControl”);
if (vc != null)
{
Form form = new Form(“video”);
form.append
((Item)vc.initDisplayMode
(vc.USE_GUI_PRIMITIVE, null));
Display.getDisplay(midlet)
.setCurrent(form);
}

p.start();

} catch (IOException ioe)
{
} catch (MediaException me)
{
}

播放RMS内存储的数据:

RecordStore rs;
int recordID;
: // code to set up the record store.

try {
InputStream is = new
ByteArrayInputStream
(rs.getRecord(recordID));
Player p = Manager.createPlayer
(is, “audio/X-wav”);
p.start();
} catch (IOException ioe)
{
} catch (MediaException me)
{
}

播放Jar文件中存储的媒体

/** Notice that in MIDP 2.0,
the wav format is mandatory only */
/** in the case that the
device supports sampled audio. */

try {
InputStream is =
getClass().getResourceAsStream
(“audio.wav”);
Player p = Manager.createPlayer
(is, “audio/X-wav”);
p.start();
} catch (IOException ioe)
{
} catch (MediaException me)
{
}

不同Player的同步

Player p1, p2;

try {
p1 = Manager.createPlayer
(“http://webserver/tune.mid”);
p1.realize();
p2 = Manager.createPlayer
(“http://webserver/movie.mpg”);
p2.realize();
p2.setTimeBase(p1.getTimeBase());
p1.prefetch();
p2.prefetch();
p1.start();
p2.start();
} catch (IOException ioe)
{
} catch (MediaException me)
{
}

产生单音序列

byte tempo = 30;
// set tempo to 120 bpm
byte d = 8;
// eighth-note

byte C4 = ToneControl.C4;
byte D4 = (byte)(C4 + 2);
// a whole step
byte E4 = (byte)(C4 + 4);
// a major third
byte G4 = (byte)(C4 + 7);
// a fifth
byte rest = ToneControl.SILENCE;
// rest

byte[] mySequence = {
ToneControl.VERSION, 1,
// version 1
ToneControl.TEMPO, tempo,
// set tempo
ToneControl.BLOCK_START, 0,
// start define “A” section
E4,d, D4,d, C4,d, E4,d,
// content of “A” section
E4,d, E4,d, E4,d, rest,d,
ToneControl.BLOCK_END, 0,
// end define “A” section
ToneControl.PLAY_BLOCK, 0,
// play “A” section
D4,d, D4,d, D4,d, rest,d,
// play “B” section
E4,d, G4,d, G4,d, rest,d,
ToneControl.PLAY_BLOCK, 0,
// repeat “A” section
D4,d, D4,d, E4,d, D4,d, C4,d
// play “C” section
};

try{
Player p = Manager.createPlayer
(Manager.TONE_DEVICE_LOCATOR);
p.realize();
ToneControl c = (ToneControl)
p.getControl(“ToneControl”);
c.setSequence(mySequence);
p.start();
} catch (IOException ioe)
{
} catch (MediaException me)
{
}

语音捕获和录音功能的实现

try
{
// Create a DataSource that
captures live audio.
Player p = Manager.createPlayer
(“capture://audio”);
p.realize();
// Get the RecordControl,
set the record location, and
// start the Player and
record for 5 seconds.
RecordControl rc =
(RecordControl)p.getControl
(“RecordControl”);
rc.setRecordLocation
(“file:/tmp/audio.wav”);
rc.startRecord();
p.start();
Thread.currentThread()
.sleep(5000);
p.stop();
rc.stopRecord();
rc.commit();
} catch (IOException ioe)
{
} catch (MediaException me)
{
} catch (InterruptedException e)
{
}

实现摄像功能

Player p;
VideoControl vc;

// initialize camera
try {
p = Manager.createPlayer
(“capture://video”);
p.realize();

// Grab the video control
and set it to the current
display.
vc = (VideoControl)p.getControl
(“VideoControl”);
if (vc != null)
{
Form form =
new Form(“video”);
form.append((Item)vc.initDisplayMode
(vc.USE_GUI_PRIMITIVE, null));
Display.getDisplay(midlet).setCurrent(form);
}

p.start();

} catch (IOException ioe)
{
} catch (MediaException me)
{
}

// now take a picture
try {
byte[] pngImage =
vc.getSnapshot(null);

// do something with the image …
} catch (MediaException me)
{
}

怎样使用MMAPI录音

try {
    // Create a Player that captures live audio.
    Player p = Manager.createPlayer("capture://audio");
    p.realize();
    // Get the RecordControl, set the record stream,
    // start the Player and record for 5 seconds.
    RecordControl rc = (RecordControl)p.getControl("RecordControl");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    rc.setRecordStream(output);
    rc.startRecord();
    p.start();
    Thread.currentThread().sleep(5000);
    rc.commit();
    p.close();
 } catch (IOException ioe) {
 } catch (MediaException me) {
 } catch (InterruptedException ie) { }

使用antenna时候的问题

编译时找不到List.deleteAll这个方法,因为默认的的antenna使用cldc1.0。而这个deleteall是1.1的方法,解决方法是覆盖默认的cldc版本

<property name=”wtk.cldc.version” value=”1.1″/>

Antenna是用来构建j2me项目的ant任务 扩展。让整个构建过程变的很简单和易于管理。

附我使用的构建脚本供参考:

<?xml version=”1.0″?>

<project name=”MoFire” default=”build” basedir=”.”>

<!– Define the Wireless Toolkit home directory. Needed by the tasks. –>

<property name=”wtk.home” value=”D:developmentWTK2.5.2″/>
<property name=”wtk.cldc.version” value=”1.1″/>
<property name=”wtk.midp.version” value=”2.0″/>
<property name=”wtk.proguard.home” value=”D:developmentworkspaceMElibproguard4.1″/>

<!– Define some additional properties for this project. Not required. –>

<property name=”midlet.name” value=”${ant.project.name}”/>
<property name=”midlet.home” value=”.”/>
<property name=”midlet.vendor” value=”MoDoFo”/>
<property name=”midlet.version” value=”0.0.1″/>
<!– Define the tasks. –>

<taskdef resource=”antenna.properties” classpath=”lib/antenna-bin-1.0.0.jar”/>

<target name=”clean”>
<delete failonerror=”false” dir=”classes”/>
</target>

<target name=”dist” depends=”build”>
<mkdir dir=”dist/${midlet.name}-${midlet.version}” />
<property name=”distfolder” value=”dist/${midlet.name}-${midlet.version}”/>
<zip destfile=”${distfolder}/${midlet.name}-${midlet.version}-src.zip”>
<fileset dir=”src” includes=”**/*.*” />
<fileset dir=”res” includes=”**/*.*” />
</zip>
<copy file=”${midlet.name}.jad” todir=”${distfolder}” />
<copy file=”${midlet.name}.jar” todir=”${distfolder}” />
<copy file=”README.txt” todir=”${distfolder}” />

<wtkrun jadfile=”${distfolder}/${midlet.name}.jad” device=”DefaultColorPhone” wait=”true”/>
</target>

<target name=”build”>

<!– Make a JAD file from scratch, don’t copy the original one. –>

<wtkjad jadfile=”${midlet.name}.jad”
name=”${midlet.name}”
vendor=”${midlet.vendor}”
version=”${midlet.version}” >

<midlet name=”MoFire”
icon=”/logo.png”
class=”com.modofo.mofire.MoFire”/>
</wtkjad>

<mkdir dir=”classes”/>

<!– Compile everything, but don’t preverify (yet). –>

<wtkbuild srcdir=”${midlet.home}/src”
destdir=”classes”
preverify=”false”/>

<!– Package everything. Most of the necessary information is
contained in the JAD file. Also preverify the result this
time. To obfuscate everything, set the corresponding
parameter to “true” (requires RetroGuard or ProGuard). The
version parameter increments the MIDlet-Version by one. –>

<wtkpackage jarfile=”${midlet.name}.jar”
jadfile=”${midlet.name}.jad”
obfuscate=”false”
autoversion=”true”>

<!– Package our newly compiled classes and the
resources from the WTK’s demo application. –>

<fileset dir=”classes”/>
<fileset dir=”${midlet.home}/res”/>

</wtkpackage>

<!– Obfuscate. –>
<!– Not needed
<wtkobfuscate jarfile=”${midlet.name}.jar”
jadfile=”${midlet.name}.jad”/>
–>
<!– Preverify things, this time separately to test the
corresponding task. –>

<wtkpreverify jarfile=”${midlet.name}.jar”
jadfile=”${midlet.name}.jad”/>

<!– Convert the JAR file into a MIDP for PalmOS PRC file. –>
<!– Not supported in wtk anymore – Zhangv
<wtkmakeprc jadfile=”${midlet.name}.jad”
prcfile=”${midlet.name}.prc”/>
–>
<!– Start the MIDlet suite –>
<!– Not need
<wtkrun jadfile=”${midlet.name}.jad” device=”DefaultColorPhone” wait=”true”/>
–>
</target>
</project>