PostMessage() alternative in Java(Android) - java

I am rewriting the existing C++ application and adapting it for Android environment.
In the code there is a PostMessage statement:
PostMessage( bExitApp ? WM_CLOSE : WM_LOGIN, wParam, lParam );
Does anyone know what is the most appropriate way to achieve tha same result in Android (Java)?
Is it well enough to create two methods like OnLogin() and OnClose() the following way:
private void OnLogin(long arg0, long arg1)
{
//some logic here
}
private void OnClose(long arg0, long arg1)
{
//some logic here
}
and then write
if(bExitApp)
(
OnLogin(arg0, arg1)
)
else
{
OnClose(arg0, arg1)
}
?

That may work. The difference is that postMessage runs after the event has been fully processed and you are back at the top of the event loop. You can simulate the behavior of PostMessage by using Handler.post(Runnable r) where you use the handler of the GUI thread.

Related

Matlab & Java: Execute matlab asynchronously

so, here is my today problem:
First of all, please note that I do NOT have the Matlab parallel toolbox available.
I am running java code witch interact with Matlab. Sometime Matlab directly call some java functions, sometimes it is the opposite. In this case, we use a notification system which comes from here:
http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events
We then address the notification in proper callbacks.
Here is a simple use case:
My user select a configuration file using the java interface, loaded into Matlab.
Using an interface listener, we notify Matlab that the configuration file has been selected, it then run a certain number of functions that will analyzes the file
Once the analysis is done, it is pushed into the java runtime, which will populate interface tables with the result. This step involve that matlab will call a java function.
Finally, java request the interface to be switched to an arbitrary decided tab.
This is the order of which things would happen in an ideal world, however, here is the code of the listener actionPerformed method:
#Override
public void actionPerformed(ActionEvent arg0) {
Model wModel = controller.getModel();
Window wWindow = controller.getWindow();
MatlabStructure wStructure = new MatlabStructure();
if(null != wModel) {
wModel.readMatlabData(wStructure);
wModel.notifyMatlab(wStructure, MatlabAction.UpdateCircuit);
}
if(null != wWindow) {
wWindow.getTabContainer().setSelectedComponent(wWindow.getInfosPannel());
}
}
What happen here, is that, when the notifyMatlab method is called, the code does not wait for it to be completed before it continues. So what happen is that the method complete and switch to an empty interface page (setSelectedComponent), and then the component is filled with values.
What I would like to, is for java to wait that my notifyMatlab returns a "I have completed !!" signal, and then pursue. Which involves asynchrounous code since Matlab will code java methods during its execution too ...
So far here is what I tried:
In the MatlabEventObject class, I added an isAcknowledge member, so now the class (which I originaly found in the above link), look like this (I removed all unchanged code from the original class):
public class MatlabEventObject extends java.util.EventObject {
private static final long serialVersionUID = 1L;
private boolean isAcknowledged = false;
public void onNotificationReceived() {
if (source instanceof MatlabEvent) {
System.out.println("Catched a MatlabEvent Pokemon !");
MatlabEvent wSource = (MatlabEvent) source;
wSource.onNotificationReceived();
}
}
public boolean isAcknowledged() {
return isAcknowledged;
}
public void acknowledge() {
isAcknowledged = true;
}
}
In the MatlabEvent class, I have added a future task which goal is to wait for acknowledgement, the methods now look like this:
public class MatlabEvent {
private Vector<IMatlabListener> data = new Vector<IMatlabListener>();
private Vector<MatlabEventObject> matlabEvents = new Vector<MatlabEventObject>();
public void notifyMatlab(final Object obj, final MatlabAction action) {
final Vector<IMatlabListener> dataCopy;
matlabEvents.clear();
synchronized (this) {
dataCopy = new Vector<IMatlabListener>(data);
}
for (int i = 0; i < dataCopy.size(); i++) {
matlabEvents.add(new MatlabEventObject(this, obj, action));
((IMatlabListener) dataCopy.elementAt(i)).testEvent(matlabEvents.get(i));
}
}
public void onNotificationReceived() {
ExecutorService service = Executors.newSingleThreadExecutor();
long timeout = 15;
System.out.println("Executing runnable.");
Runnable r = new Runnable() {
#Override
public void run() {
waitForAcknowledgement(matlabEvents);
}
};
try {
Future<?> task = service.submit(r);
task.get(timeout, TimeUnit.SECONDS);
System.out.println("Notification acknowledged.");
} catch (Exception e) {
e.printStackTrace();
}
}
private void waitForAcknowledgement(final Vector<MatlabEventObject> matlabEvents) {
boolean allEventsAcknowledged = false;
while(!allEventsAcknowledged) {
allEventsAcknowledged = true;
for(MatlabEventObject eventObject : matlabEvents) {
if(!eventObject.isAcknowledged()) {
allEventsAcknowledged = false;
}
break;
}
}
}
}
What happen is that I discover that Matlab actually WAIT for the java code to be completed. So my waitForAcknowledgement method always wait until it timeouts.
In addition, I must say that I have very little knowledge in parallel computing, but I think our java is single thread, so having java waiting for matlab code to complete while matlab is issuing calls to java functions may be an issue. But I can't be sure : ]
If you have any idea on how to solve this issue in a robust way, it will be much much appreciated.

Fire Change Event source is NULL in GWT

When clicking an Button it need to perform click action in this action should perform change event at this event source is null
My Code:
Multiview.java
#Override
public void onClick(ClickEvent event) {
if(event.getSource() instanceof PushButton)
{
PushButton pb = (PushButton)event.getSource();
if (id.equals("New")) {
int rowNO = startRow + tableModel.rows() - 1;
Window.selectedRow = rowNO;
Window.selectedNode = m_node;
Window.tabNo = multicomponentVO.tabNo;
Window.tabVO = tabfieldsVO;
Window.selectedqueryID=queryID;
Window.cVO = multicomponentVO;
Window.selectedcVO=multicomponentVO;
fireChange("viewnew");
}
}
private void fireChange(String action) {
this.action = action;
if (changeListeners != null) {
changeListeners.fireChange(new ChangeEvent(){});
}
}
Window.java
#Override
public void onChange(ChangeEvent event) {
Widget sender=(Widget)event.getSource();
if(sender instanceof Multiview)
{
// some stuff
}
My query is When firing change event in multiview.java it fires onchange in window.java but im getting event source is null.
Please anyone help to refine or resolve this query
Several issues are contributing to this.
changeListeners.fireChange(new ChangeEvent(){});
You've taken over how the even is supposed to be fired - instead of actually going through the event wiring that would do it right, you've made an object with no source, passed it to fireChange (which I bet is one of your own methods in changeListeners), though you don't have it listed, unless Multiview.fireChange is calling itself...?), and then are complaining that it has no source! Consider firing either from the widget (I'm assuming Mulitview is a widget), or making a handlerManager/eventBus inside Multiview and using that to send the event.
Next, you are firing a DOM event manually, which is a little weird - this is an event that is meant to be fired from user actions in the browser. Take a look at ValueChangeEvent<T> instead.

Save on change of CommandStack

probably a really easy newbie question but I can't manage to get it for already a pair of days, so I'll aks it here. My scope: I have an RCP application with some Graphical Editors (extensions of EditorPart). In my editor I want to catch any changes and save them directly. For that I catch the moment in which my CommandStack gets changed and start a doSave method. The problem is that my save method calls a CommadStack change event and if i skip this call than my changes are saved but my editor has still got a dirty flag. My wished behaviour would be that the dirty flag is away(like a normal save behaviour).
Both my CommandStack change and my doSave method are below. Could you please help me?
#Override
public void commandStackChanged(EventObject event) {
firePropertyChange(IEditorPart.PROP_DIRTY);
doSave(null);
setDirty(false);
}
public void doSave(final IProgressMonitor progressMonitor) {
editorSaving = true;
SafeRunner.run(new SafeRunnable() {
public void run() throws Exception {
IFile targetFile = getFile();
List<GraphicalEditPart> editParts = DiagramUtil.getAllEditParts(NetEditor.this);
Rectangle offsetBounds = DiagramUtil.getBounds(editParts);
saveDiagramProperties();
List<INetTransition> transitionsToExpand = saveSubdiagramGroups();
FileUtil.saveDiagram(getNetDiagram(), targetFile,
NetEditor.this);
getCommandStack().markSaveLocation();
for (INetTransition trans : transitionsToExpand) {
trans.setExpanded(true);
}
}
});
setDirty(false);
editorSaving = false;
}
With getCommandStack().markSaveLocation() I call once more the commandStackChanged and get in a loop. How can I solve this problem? Without it my editor remains dirty after save.
Thanks and Greets,
Jeff
How about adding IPropertyListener to your Editor and listen for IEditorPart.PROP_DIRTY. For the listener implementation perform save if editor is dirty otherwise do nothing.

In ZK, How do I adjust UI component according to orientation of the mobile device?

I'm using ZK6, and I would like to change my UI component according to orientation of the mobile device.
In ZK component reference : Tablet Devices/Events/ClientInfoEvent , there is a getOrientation() method in ClientInfoEvent. However, I did not see this method in the class, nor could I find any information about this method. (see update)
Right now I am using this piece of code to adjust component size when device orientation changed.
#Override
public void doAfterCompose(Groupbox comp) throws Exception {
super.doAfterCompose(comp);
comp.addEventListener(Events.ON_CLIENT_INFO, new EventListener<ClientInfoEvent>() {
#Override
public void onEvent(ClientInfoEvent event) throws Exception {
getSelf().setHeight(event.getScreenHeight() + "px");
getSelf().setWidth(event.getScreenWidth() + "px");
}
});
}
But I'm not quite satisfy with it because it require server to update the component, and I still don't know what orientation it is.
So, how do I know orientation ? and what is a better way to adjust component size according these information ?
I use android emulator to test, if that matters.
UPDATE
I notice that getOrientation() are implement in version 6.5.0, which is not from a stable release.
Since 6.5.0 has been released a while, I decide to answer this question.
Basically, ClientInfoEvent now provide information about orientation, and also
device pixel ratio
so now we can write code like this :
#Override
public void doAfterCompose(Groupbox comp) throws Exception {
super.doAfterCompose(comp);
comp.addEventListener(Events.ON_CLIENT_INFO, new EventListener<ClientInfoEvent>() {
#Override
public void onEvent(ClientInfoEvent event) throws Exception {
if (event.isLandscape()) {
// do things when landscape
} else {
// do other things else.
}
}
});
}
For re-size component, I wrote some client side code to adjust widget width/height at client side, and use java code to ask server to update component if necessary.

JAVA JNA WindowProc implementation

I'm trying to write a simple application in Java that will communicate with an USB device. The USB device is made by me using a Microchip Microcontroller. The communication is rather simple, since the USB device is from the HID Class, arrays of 64 bytes are exchanged between the computer and the device.
My program finds the device based on the product ID and the vendor ID, can write and read 64 bytes, but now I would like to detect when the device is connected or disconnected from the computer.
As I've seen in a C# program provided by Microchip as an example application, the WndProc method is overriden and the WM_DEVICECHANGE message is handled. My question is how can this be done in Java using JNA, how can I override the WindowProc Method and handle messages, if this is possible at all :), but I hope it is :D
Thanks in advance for the answers.
Gabor.
I finally managed to solve the problem :) And I found the following solution:
First extend the User32 interface in the following way
public interface MyUser32 extends User32 {
public static final MyUser32 MYINSTANCE = (MyUser32) Native.loadLibrary("user32", MyUser32.class, W32APIOptions.UNICODE_OPTIONS);
/**
* Sets a new address for the window procedure (value to be set).
*/
public static final int GWLP_WNDPROC = -4;
/**
* Changes an attribute of the specified window
* #param hWnd A handle to the window
* #param nIndex The zero-based offset to the value to be set.
* #param callback The callback function for the value to be set.
*/
public int SetWindowLong(WinDef.HWND hWnd, int nIndex, Callback callback);
}
Then extend the WinUser interface with the Windows Message code that you need, in my case this is the WM_DEVICECHANGE, because I want to check I the USB Device was attached or detached from the computer.
public interface MyWinUser extends WinUser {
/**
* Notifies an application of a change to the hardware configuration of a device or the computer.
*/
public static final int WM_DEVICECHANGE = 0x0219;
}
Then create an interface with the callback function, which will actually be my WndProc function.
//Create the callback interface
public interface MyListener extends StdCallCallback {
public LRESULT callback(HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam);
}
public MyListener listener = new MyListener()
{
public LRESULT callback(HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam)
{
if (uMsg == MyWinUser.WM_DEVICECHANGE)
{
// TODO Check If my device was attached or detached
return new LRESULT(1);
}
return new LRESULT(0);
}
};
And then somewhere in the code of the JFrame where you initialize things add the new address for the window procedure with the SetWindowLong function:
// Get Handle to current window
HWND hWnd = new HWND();
hWnd.setPointer(Native.getWindowPointer(this));
MyUser32.MYINSTANCE.SetWindowLong(hWnd, MyUser32.GWLP_WNDPROC, listener);
This code works nicely, but I have some doubts regarding one thing. I'm not sure if the return value of the callback function is correct. I've read in the MSDN that after handling a WM_DEVICECHANGE message the callback function should return true and I'm not sure that the value i'm currently returning is the one expected by the system, so any suggestions are welcome.
If anyone is interested in the whole code I've written for the HID communication just ask, I would be more than happy to help :)
Cheers,
Gabor.
If you don't have an existing window handle you have to create your own window first. And when you create a new window you also have to manage its message pump. Here's an example on how you can do this. JNA's own example code could also be very useful.
Thread thread;
HWND hWnd;
static final int WM_NCCREATE = 0x0081;
void start() {
thread = new Thread(this::myThread);
thread.start();
}
void stop() {
User32.INSTANCE.PostMessage(hWnd, User32.WM_QUIT, null, null);
}
WindowProc callback = new WindowProc() {
#Override
public LRESULT callback(HWND hWnd, int uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_NCCREATE:
return new LRESULT(1);
case User32.WM_DEVICECHANGE:
return new LRESULT(1);
default:
return new LRESULT(0);
}
}
};
void myThread() {
WString className = new WString("myclass");
WNDCLASSEX wx = new WNDCLASSEX();
wx.clear();
wx.lpszClassName = className;
wx.lpfnWndProc = callback;
if (User32.INSTANCE.RegisterClassEx(wx).intValue() != 0) {
hWnd = User32.INSTANCE.CreateWindowEx(0, className, null, 0, 0, 0, 0, 0, null, null, null, null);
WinUser.MSG msg = new WinUser.MSG();
msg.clear();
while (User32.INSTANCE.GetMessage(msg, hWnd, 0, 0) > 0) {
User32.INSTANCE.TranslateMessage(msg);
User32.INSTANCE.DispatchMessage(msg);
}
}
}
You can create COM DLL or OCX of your C# program and use it in the java code. If you create application.
Use JACOB OR JCOM
It will be a bridge between Java and COM Object. Other option is you can use JNI to communicate with DLL and OCX.
The solution I posted previously has some problems, unfortunately :(
Since it overrides the WndProc of the window, the controls I added to my Frame weren't working (not surprisingly, because no paint, repaint, etc. messages were handled). Then I realised that instead of returning LRESULT(1) I should call the default window proc (as it is used in Win32 C++ programs), but this still didn't solve the problem, the frame was painted but the buttons weren't working, although I was able to update labels... So I had to abandon this solution too.
After searching some more on the internet I've found a great article here (edit: link is dead, original article can be found here), where a static hidden window is created to handle windows messages. I managed to code it for my application and it works great. (I had to further extend the classes from JNA because several functions were not included. I can post my code if someone is interested.)
Hope this helps.

Categories

Resources