Thread.sleep (change image) Java - thread-sleep

I have two jlabels with an image.. I try to change the image in a label when the other is clicked.. (such as a game)..
I have a problem..When i write the Thread.sleep the image is not change..See the code:
public class Game extends JFrame{
private JLabel l1,l2;;
private boolean isClicked = false ,isClicked2 = false;
public Game(){
setLayout(new FlowLayout());
l1 = new JLabel(new ImageIcon(getClass().getResource("image1.png")));
add(l1);
l2 = new JLabel(new ImageIcon(getClass().getResource("image1.png")));
add(l2);
l1.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {
if(isClicked2){
l1.setIcon(new ImageIcon(getClass().getResource("image2.png")));
try {
Thread.sleep(1000);
l1.setIcon(new ImageIcon(getClass().getResource("image1.png")));
l2.setIcon(new ImageIcon(getClass().getResource("image1.png")));
isClicked2 = false;
isClicked = false;
}catch(InterruptedException ex){}
}
else{
l1.setIcon(new ImageIcon(getClass().getResource("image2.png")));
isClicked = true;
}
}#Override public void mouseEntered(MouseEvent e){}#Override public void mouseExited(MouseEvent e){}
});
l2.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {
if(isClicked){
try {
l2.setIcon(new ImageIcon(getClass().getResource("image2.png")));
Thread.sleep(1000);
l2.setIcon(new ImageIcon(getClass().getResource("image1.png")));
l1.setIcon(new ImageIcon(getClass().getResource("image1.png")));
isClicked = false;
isClicked2 = false;
}catch(InterruptedException ex){}
}
else{
l2.setIcon(new ImageIcon(getClass().getResource("image2.png")));
isClicked2 = true;
}
}#Override public void mouseEntered(MouseEvent e){}#Override public void mouseExited(MouseEvent e){}
});
}
public static void main(String[] args) {
Game g = new Game();
g.setTitle("Fint the same");
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.pack();
g.setVisible(true);
}
}
Run it and first click the fisrt label.. After click the second label and the first will change image in 1 second but the seconf label NEVER!!

The changing of the images has to be done on the event thread (the thread used to process graphics events). Therefore setting the image will queue an appropriate event to be processed after your method returns. At that time though, the image has already changed back, because sleep()ing on the event thread doesn't allow any other events to be processed.
As dashrb said, don't sleep() the main thread, but schedule the flip back in a Timer:
if (isClicked) {
l2.setIcon(new ImageIcon(getClass().getResource("image2.png")));
new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
l2.setIcon(new ImageIcon(getClass().getResource("image1.png")));
l1.setIcon(new ImageIcon(getClass().getResource("image1.png")));
isClicked = false;
isClicked2 = false;
}
}).start();
} catch (final Exception ex) {
ex.printStackTrace();
}
} else {
...

You should not sleep() in these methods--they are invoked from the "event dispatch" thread, which handles all drawing events. If you're sleeping, then the thread can't be repainting your labels.
Rather than sleeping, change your image, then create a javax.swing.Timer task which will fire 1-second-from-now to change the images again as desired. The sample from koljaTM above uses a java.util.Timer, which runs in the "wrong" thread. This is his code, modified to use a SWING timer:
if (isClicked) {
try {
l2.setIcon(new ImageIcon(getClass().getResource("image2.png")));
javax.swing.Timer timer = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
l2.setIcon(new ImageIcon(getClass().getResource("image1.png")));
System.out.println("image2 gone");
l1.setIcon(new ImageIcon(getClass().getResource("image1.png")));
isClicked = false;
isClicked2 = false;
}
});
timer.setRepeats(false);
timer.start();
} catch (final Exception ex) {
ex.printStackTrace();
}
} else {
...

Related

Suspended (exception IlegalStateException) blackberry 6.0

Following is the code which is showing the above exception on debugging :
Firstly I am trying to call a class HTTPConnection from the below menu item.
protected MenuItem _SelectDealerItem = new MenuItem("Select Dealer",100,10)
{
public void run()
{
new HTTPConnection();
}
};
In HTTPConnection Class I am checking the connection type and calling another Class TSelectDealerScreen:
public class HTTPConnection {
ConnectionFactory _factory = new ConnectionFactory();
public HTTPConnection()
{
int[] _intTransports = {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_WAP2,
TransportInfo.TRANSPORT_TCP_CELLULAR
};
for(int i=0;i<_intTransports.length;i++)
{
int transport = _intTransports[i];
if(!TransportInfo.isTransportTypeAvailable(transport)||!TransportInfo.hasSufficientCoverage(transport))
{
Arrays.removeAt(_intTransports,i);
}
}
TcpCellularOptions tcpOptions = new TcpCellularOptions();
if(!TcpCellularOptions.isDefaultAPNSet())
{
tcpOptions.setApn("My APN");
tcpOptions.setTunnelAuthUsername("user");
tcpOptions.setTunnelAuthPassword("password");
}
if(_intTransports.length>0)
{
_factory.setPreferredTransportTypes(_intTransports);
}
_factory.setTransportTypeOptions(TransportInfo.TRANSPORT_TCP_CELLULAR, tcpOptions);
_factory.setAttemptsLimit(5);
Thread t = new Thread(new Runnable()
{
public void run()
{
ConnectionDescriptor cd = _factory.getConnection("http://excellentrealtors.info/Smart-Trace/get_dealer.php");
if(cd!=null)
{
Connection c = cd.getConnection();
displayContent(c);
}
}
});
t.start();
}
private void displayContent(final Connection conn)
{
UiApplication.getUiApplication().pushScreen(new TSelectDealerScreen(conn));
}
}
In TSelectDealerScreen class i am simply trying to read the stream, but it is showing illegal state exception whenever i try to debug, I am not much familiar to blackberry programming, kindly advice.
public class TSelectDealerScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public TSelectDealerScreen(Connection conn)
{
_rtfOutput.setText("Retrieving Data.Please Wait");
add(_rtfOutput);
ContentReaderThread t = new ContentReaderThread(conn);
t.start();
}
private final class ContentReaderThread extends Thread {
private Connection _connection;
ContentReaderThread(Connection conn)
{
_connection = conn;
}
public void run()
{
String result = "";
OutputStream os = null;
InputStream is = null;
try
{
OutputConnection outputConn = (OutputConnection)_connection;
os = outputConn.openOutputStream();
String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
os.write(getCommand.getBytes());
os.flush();
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) _connection;
is = inputConn.openInputStream();
byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
result = new String(data, "US-ASCII");
// is.close();
System.out.print(result);
}
catch(Exception e)
{
result = "ERROR fetching content: " + e.toString();
}
finally
{
// Close OutputStream
if(os != null)
{
try
{
os.close();
}
catch(IOException e)
{
}
}
// Close InputStream
if(is != null)
{
try
{
is.close();
}
catch(IOException e)
{
}
}
// Close Connection
try
{
_connection.close();
}
catch(IOException ioe)
{
}
}
// Show the response received from the web server, or an error message
showContents(result);
}
}
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
In your HTTPConnection class, you do:
Thread t = new Thread(new Runnable()
{
public void run()
{
ConnectionDescriptor cd = _factory.getConnection("http://excellentrealtors.info/Smart-Trace/get_dealer.php");
if(cd!=null)
{
Connection c = cd.getConnection();
displayContent(c);
}
}
});
t.start();
That runs everything inside run() on a background thread. But, inside displayContent(c), you do:
UiApplication.getUiApplication().pushScreen(new TSelectDealerScreen(conn));
which is a UI operation.
Trying to modify the UI from a background thread normally causes an IllegalStateException.
I believe you just need to wrap the call to pushScreen() with this:
private void displayContent(final Connection conn) {
final UiApplication app = UiApplication.getUiApplication();
app.invokeLater(new Runnable() {
public void run() {
// this code is run on the UI thread
app.pushScreen(new TSelectDealerScreen(conn));
}
});
}
Also, if you're an Android developer, and you want help doing normal background/UI thread stuff, you might check out this other answer I wrote on "porting" AsyncTask to BlackBerry Java

how to increase performance to load images from SDCard to my application?

Hi i made one small application to show all sdcard images should display in my application as Thumbnail view .my program is like following
Here problem is that in simulator it loads fast and accurate where as phone it take lots of time. it is loaded some of 30MB around not getting problem. whare it is 80MB around it is not showing images on my screen.
Note: This is perfectly working in simulator but Not device
and my images path is "file:///SDCard/images/"
My code is:
this is my application starter class
public class StartUp extends UiApplication{
public static void main(String[] args) {
StartUp start=new StartUp();
start.enterEventDispatcher();
}
public StartUp() {
pushScreen(new ViewerMainScreen());
}
}
this is my ViewerMainScreen.java
public class ViewerMainScreen extends MainScreen implements FieldChangeListener{
private ObjectListField fileList;
private String currentPath = "file:///";
public VerticalFieldManager vert_manager=null;
private BitmapField before[]=null,next[]=null;
private int size=0;Border b1,b2;
TableLayoutManager colFMgr=null;
private Vector img_data=null;
private int count=0;
public ViewerMainScreen() {
super();
setTitle("Browse to image...");
initGUI();
}
public void initGUI() {
try {
// add(getFileList());
img_data=getAllList("file:///SDCard/images");
b1=BorderFactory.createSimpleBorder(new XYEdges(3,3,3,3),new XYEdges(Color.RED, Color.RED, Color.RED, Color.RED),Border.STYLE_SOLID);
b2=BorderFactory.createSimpleBorder(new XYEdges(0,0,0,0));
size=img_data.size();
before=new BitmapField[size];
next=new BitmapField[size];
vert_manager=new VerticalFieldManager(VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(),Display.getHeight());
}
};
colFMgr = new TableLayoutManager(new int[] {
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
}, Manager.HORIZONTAL_SCROLL|VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
for(int i= 0;i < size;i++)
{
EncodedImage load_img=EncodedImage.getEncodedImageResource("loading.jpg");
before[i] = new BitmapField(load_img.getBitmap(),Field.FOCUSABLE){
protected boolean navigationClick(int status,int time) {
fieldChangeNotify(0);
return super.navigationClick(status, time);
}
protected void onFocus(int direction)
{
this.setBorder(b1);
invalidate();
}
protected void onUnfocus()
{
this.setBorder(b2);
invalidate();
}
};
colFMgr.add(before[i]);
}
add(colFMgr);
Thread t=new Thread(){
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
callImageThread();
}
};
t.start();
} catch (Exception e) {
Dialog.alert(e.getMessage());
}
}
private void callImageThread() {
for(int i=0;i<size;i++)
{
if(count==6){
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageThread th=new ImageThread(this, "file:///SDCard/images/"+img_data.elementAt(i), i);
th.start();
count++;
}
}
public void ReplaceImage(EncodedImage img,int index)
{
before[index].setBitmap(img.getBitmap());
before[index].setChangeListener(this);
count--;
System.out.println("Thread count: ========================"+Thread.activeCount()+"============================================="+count);
}
public void fieldChanged(Field field, int context) {
for(int i=0;i<size;i++)
{
if(field==before[i])
{
synchronized (UiApplication.getEventLock()) {
EncodedImage img=null;
img=loadFile("file:///SDCard/images/"+img_data.elementAt(i));
int displayWidth = Fixed32.toFP(Display.getWidth()-100);
int imageWidth = Fixed32.toFP(img.getWidth());
int scalingFactorX = Fixed32.div(imageWidth, displayWidth);
int displayHeight = Fixed32.toFP(Display.getHeight()-100);
int imageHeight = Fixed32.toFP(img.getHeight());
int scalingFactorY = Fixed32.div(imageHeight, displayHeight);
EncodedImage scaledImage = img.scaleImage32(scalingFactorX, scalingFactorY);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(scaledImage));
}
}
}
}
public void displayMessage(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform(message);
}
});
}
private Vector getAllList(String path){
Vector data=new Vector();
FileConnection fileConnection=null;
try{
fileConnection = (FileConnection) Connector.open(path);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list();
while (directoryEnumerator.hasMoreElements()) {
data.addElement(directoryEnumerator.nextElement());
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return data;
}
private EncodedImage loadFile(String path) {
FileConnection fileConnection =null;
InputStream inputStream =null;
EncodedImage encodedImage=null;
try {
fileConnection = (FileConnection) Connector.open(path);
if(fileConnection.exists()){
inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int)fileConnection.fileSize()];
inputStream.read(imageBytes);
encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (IOException e) {
Dialog.alert("Insert an SD Card.");
}
return encodedImage;
}
}
This is my ImageThread.java
public class ImageThread extends Thread{
private ViewerMainScreen screen;
private String path;
private int index;
private EncodedImage scaledImage=null;
public ImageThread(ViewerMainScreen screen,String path,int index) {
this.screen=screen;
this.path=path;
this.index=index;
}
public void callMainScreen(EncodedImage eimg,int Rindex) {
screen.ReplaceImage(eimg, Rindex);
}
public void run() {
FileConnection fileConnection =null;
InputStream inputStream =null;
EncodedImage encodedImage=null;
try {
fileConnection = (FileConnection) Connector.open(path);
if(fileConnection.exists()){
inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int)fileConnection.fileSize()];
inputStream.read(imageBytes);
encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
int displayWidth = Fixed32.toFP(100);
int imageWidth = Fixed32.toFP(encodedImage.getWidth());
int scalingFactorX = Fixed32.div(imageWidth, displayWidth);
int displayHeight = Fixed32.toFP(100);
int imageHeight = Fixed32.toFP(encodedImage.getHeight());
int scalingFactorY = Fixed32.div(imageHeight, displayHeight);
scaledImage = encodedImage.scaleImage32(scalingFactorX, scalingFactorY);
callMainScreen(scaledImage, index);
}
} catch (IOException e) {
Dialog.alert("Insert an SD Card.");
}
finally
{
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
please help me how to increase performance of my code
I would load images only when user scrolls screen. For example load first two screens on screen start (in different thread) and load next when user is moving down. So set ScrollListener to your manager and use field postion and height to determine which is on the screen and which is going to be on screen soon.
Also use limited size thread pool and queue for images loading. Unfortunately java concurrent is not par of j2me. But there are several similar pattern implementations, like ThreadPool.
And It would be super if you also remember case when user scrolls fast - cancel scheduled loading if it's not required. For every loading task remember BitmapField position and size. Before task starts file loading check if BitmapField is visible (going to be visible) with current scroll position.
Also be aware about threads count. I see that you try to sleep main loading thread when count is 6. But there is still small possibility that 400 ms is not enough to finish work for current threads and you can easily start to create more threads.
Also minor things - use Bitmap.scaleInto (If you target is 5.0+), use synchronization around size field, next is never used, use a little better names like nextImages, threadsCount, etc.

blackberry buttonfield navigate on 2 second hold

I am developing a blackberry app. I want to open an screen from the home screen when user will press one button and hold it for 2 seconds.
Any way?
Thanks.
Here is the code for your question. I have make use of this BlackBerry LongClickListener implementation link which contains good explanation too.
public class HoldButtonScreen extends MainScreen implements FieldChangeListener {
ButtonField _btnHold;
Timer _timer;
public HoldButtonScreen() {
_btnHold = new ButtonField("Hold 2 sec to get popup")
{
protected boolean navigationClick(int status, int time) {
final Field _btnHold= this;
_timer = new Timer();
System.out.println("hi there");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try{
_timer.schedule(new TimerTask() {
public void run() {
fieldChanged(_btnHold, 0);
}}, 2000);
}catch(Exception e){
e.printStackTrace();
}
}
});
return true;
}
protected boolean navigationUnclick(int status, int time) {
System.out.println("hi unclick");
add(new LabelField("You have't hold button for 2 second."));
_timer.cancel();
return true;
}
};
_btnHold.setChangeListener(this);
add(_btnHold);
}
public void fieldChanged(Field field, int context) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
PopupScreen _popUpScreen = new PopupScreen(new VerticalFieldManager()){
public boolean onClose() {
close();
return true;
}
};
_popUpScreen.add(new LabelField("Hello , i am pop up after 2 second."));
UiApplication.getUiApplication().pushScreen(_popUpScreen);
}
});
}
}
Try this this will run successfully.
Just change the Screen in PushScreen.
private Thread splashTread;
protected int _splashTime = 200;
boolean countinue = true;
splashTread = new Thread() {
public void run() {
while (countinue == true) {
try {
synchronized (this) {
wait(_splashTime);
}
} catch (InterruptedException e) {
} finally {
synchronized (UiApplication.getUiApplication().getAppEventLock()) {
UiApplication.getUiApplication().pushScreen(new Login());
SplashScreen.this.close();
}
countinue = false;
}
}
}
};
splashTread.start();

Adding Editfield to Popup screen

I have created my own custom popup screen to which now I am trying to add a editfield , everything seems to be fine but the problem is that I am not able to write anything in the edit field
class sveetIt extends PopupScreen implements FieldChangeListener, DialogClosedListener {
Hashtable pitemData;
ButtonField sveetNowlabelField;
ButtonField sveetLaterlabelField;
WatingScreen watingScreen;
long scheduledTime;
Dialog updateDialog;
public sveetIt() {
super(new MyCustimGridFieldManager());
LabelField messageLabelField = new LabelField("Enter your Sveet Message:",Field.FIELD_HCENTER) {
protected void paint(Graphics graphics) {
graphics.setColor(Color.YELLOWGREEN);
super.paint(graphics);
}
};
EditField sveetTexteditField= new EditField(null, "Sveet Message", 50, EditField.FIELD_HCENTER
| EditField.FIELD_VCENTER
| EditField.NON_SPELLCHECKABLE | EditField.NO_NEWLINE);
VerticalFieldManager buttonVFManager = new VerticalFieldManager(VerticalFieldManager.FIELD_HCENTER);
HorizontalFieldManager hfManager = new HorizontalFieldManager();
sveetNowlabelField = new ButtonField("Sveet Now");
sveetLaterlabelField = new ButtonField("Sveet Later");
sveetNowlabelField.setChangeListener(this);
sveetLaterlabelField.setChangeListener(this);
add(messageLabelField);
add(sveetTexteditField);
hfManager.add(sveetNowlabelField);
hfManager.add(sveetLaterlabelField);
buttonVFManager.add(hfManager);
add(buttonVFManager);
}
public boolean isEditable() {
return true;
}
protected boolean keyChar(char c, int status, int time) {
boolean retVal = false;
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
retVal = super.keyChar(c, status, time);
}
return retVal;
}
public void fieldChanged(Field field, int context) {
if (sveetNowlabelField == field) {
//Here directly starts uploading file
beginUpload();
} else if (sveetLaterlabelField == field) {
// first picks up time when to upload
scheduledTime = getScheduleTime();
if(scheduledTime!=1L) {
//now begins uploading file
beginUpload();
}
}}
class SubscribingThread extends StoppableThread {
int network = 50;
public void run() {
}
}
public void beginUpload() {
try {
watingScreen = new WatingScreen("Uploading Sveet...");
/*
* UiApplication.getUiApplication().invokeAndWait( new Runnable() {
* public void run() { Ui.getUiEngine().pushScreen(watingScreen); }
* });
*/
BaseScreen.pushScreen(watingScreen);
Thread thread = new Thread(new Runnable() {
public void run() {
uploadToServer();
}
});
thread.start();
// uploadToServer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private long getScheduleTime() {
scheduledTime = 0;
final DateTimePicker datePick = DateTimePicker.createInstance();
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Calendar currentCalendar = datePick.getDateTime();
datePick.setMinimumDate(currentCalendar);
datePick.doModal();
Calendar cal = datePick.getDateTime();
if (cal.after(currentCalendar)) {
Date date = cal.getTime();
Dialog.alert("You selected " + date.toString());
scheduledTime = date.getTime();
} else {
Dialog.alert("Invalid date selection");
scheduledTime = 1L;
}
}
});
System.out.println("date in MilliSeconds is:" + scheduledTime);
return scheduledTime;
}
public void uploadToServer() {
} public void dialogClosed(Dialog arg0, int arg1) {
}
}
class MyCustimGridFieldManager extends VerticalFieldManager {
public MyCustimGridFieldManager() {
super(VERTICAL_SCROLL | USE_ALL_WIDTH | FIELD_HCENTER);
}
protected void paint(Graphics gr) {
super.paint(gr);
}
}
try this:
protected boolean keyChar(char c, int status, int time) {
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
}
return super.keyChar(c, status, time);
}
Try adding Field.EDITABLE to your style for the EditField.

updated on image

i am developing an application that use some images. We require some text print on image but that is not a fixed mean when change the variable value automatically change the text. Simply we say that we print a variable on image?
try this
public class Test extends UiApplication {
public static void main(String[] arg) {
Test app = new Test();
app.enterEventDispatcher();
}
public Test() {
MyScreen screen = new MyScreen();
pushScreen(screen);
}
}
class MyScreen extends MainScreen {
LabelField label;
public MyScreen() {
label = new LabelField() {
protected void paint(Graphics g) {
Bitmap bitmap = Bitmap.getBitmapResource("bgimage.jpg");
g.drawBitmap(0, 0, getWidth(), getHeight(), bitmap, 0, 0);
super.paint(g);
}
};
ButtonField button = new ButtonField("update") {
protected void fieldChangeNotify(int context) {
update();
super.fieldChangeNotify(context);
}
};
add(label);
add(button);
}
public void setMessage(String message) {
synchronized (UiApplication.getEventLock()) {
label.setText(message);
}
}
private void update() {
LocationHandler handler = new LocationHandler(this);
handler.start();
}
}
class LocationHandler extends Thread {
private MyScreen screen;
public LocationHandler(MyScreen screen) {
this.screen = screen;
}
public void run() {
Criteria criteria = new Criteria();
criteria.setVerticalAccuracy(50);
criteria.setHorizontalAccuracy(50);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
try {
LocationProvider provider = LocationProvider.getInstance(criteria);
Location location = provider.getLocation(-1);
String speed = location.getSpeed() + "m/s";
screen.setMessage(speed);
} catch (LocationException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Resources