相信做手机开发的朋友都知道,手机上有一个连续按键的处理,j2me规范里面也提供了一个方法给予支持。现在市场上主流的机都支持了连续
按键,比如Nokia的S60系列,S40系列也是很多支持的,Nokia6600则不支持。国产品牌等机子的有些虚拟机不支持连续按键。
对于不支持连续按键的机子来说。用户操作时很不习惯的,特别是浏览一页比较大的文档,或者是玩手机游戏的用户来说。真是太不爽了,
有没有办法解决这个问题啊。有,那就是采用轮询的机制进行模拟连续按键。
说下原理吧:
其实很简单的,
只要在按下键盘的是做一个flag。
离开键盘的是做下flag。
启动一个线程进行监控,就可以了。
具体看代码吧。

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Display;

public class TestCanvas extends MIDlet {
    public TestCanvas() {
    }
    protected void startApp() throws MIDletStateChangeException {
        Display.getDisplay(this).setCurrent(new TCanvas());
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean _boolean) throws
            MIDletStateChangeException {
    }

}

class TCanvas extends Canvas {
    int key;
    boolean supper;
    boolean isKeyDown;
    long timeOut;
    public TCanvas() {
        new Thread(
                new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                    }
                    if (isKeyDown) {
                        long curTime = System.currentTimeMillis();
                        if (curTime - timeOut >= 300) {
                            timeOut = curTime;
                            System.out.println("keyReleased==>" + key);
                            repaint();
                        }
                    }
                }
            }
        }
        ).start();
    }
    protected void paint(Graphics graphics) {
        graphics.setColor(0x0);
        graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
        graphics.setColor(0xFFFFFF);
        graphics.drawString("key==>" + key, 50, 50, 20);
        //  System.out.println("事件==>" + key);
    }
    protected void keyPressed(int keyCode) {
        this.key = keyCode;
        System.out.println("keyPressed==>" + key);
        isKeyDown = true; //长按
        this.repaint();
    }
    protected void keyRepeated(int keyCode) {
        this.key = keyCode;
        System.out.println("keyRepeated==>" + key);
        this.repaint();
    }
    protected void keyReleased(int keyCode) {
        isKeyDown = false;
        this.key = keyCode;
        System.out.println("keyReleased==>" + key);
        this.repaint();
    }

}