Fire an event in Android/AndEngine? - android

I have a 'trick' that I do sometimes in Java/Swing in which I create a swing component that is always invisible and have property change event listener(s) attached to it. When a variable(s) changes value, the code will cause that component to change and fire an event and anything listening will know that those variable(s) have changed.
I want to do this same thing in Android or AndEngine. What would I use instead of the swing component? I'm was thinking of overriding some subclass of org.andengine.entity.Entity, but I don't see any event to fire.

Sounds like you almost hit on it with your Swing idea. There is no event pattern built into andengine, and the reason for this is probably because of the event classes built into the android operating system.
You should have good luck implementing a Listener (Observer Pattern) into your app following the steps in this other Stack Overflow answer:
Custom event listener on Android app
or this simple example in which the broadcaster call a function on a single listener:
Android - event listener
As a footnote, neither example includes code to REMOVE listeners. Be sure your implementation does include that so that you can garbage collect objects you don't need any more.

Related

Flutter: How do I call a function in widget A from widget B when the widgets do not have a parent/child relationship?

I have the following structure for my app, where ChatScreen contains the ChatHeader and the ChatFooter.
---ChatHeader.dart --- MessageDao.dart
ChatScreen.dart ---
---ChatFooter.dart
In the ChatHeader widget, I call another widget called MessageDao.dart. This widget generates the button that the user can press on the ChatHeader widget to play audio.
In the ChatFooter widget, this widget contains a different button that the user can press to record using their mic.
When I play audio using the button from ChatHeader -> MessageDao, this works just fine. However, if I click the button in the ChatFooter widget to start recording while in the middle of playing audio from the first button, this audio doesn't stop playing. It keeps playing while I'm recording. I have a stopPlaying() function in MessageDao that I can use, but I'm not sure how to call a function in widget A from widget B.
Or in other words, how do I call MessageDao.stopPlaying() from inside ChatFooter.dart?
With this type of situation, the ideal solution is to take a page out of React and 'lift the state up'; this means that whatever method is on the child should be lifted to a higher node in the widget tree (e.g. ChatScreen) and then pass the function down to the nodes that use it (ChatHeader and ChatFooter). You could also try leveraging InheritedWidget after 'lifting state up' and avoid sending methods down a chain of widgets.
Now, this is a recurring theme with Flutter apps (and overall declarative frameworks) and is a problem that can have multiple solutions. My suggestion would be that you take a look at different state management options like bloc, provider, mobx, riverpod, rxdart, redux or event_bus_plus just to mention a few. Said libraries will give you the abstractions you need for each use case and help you avoid implementing really complex logic that you might need to solve problems similar to this one by yourself.
Of course, this is an important decision for your project so I suggest you take a good look and choose whatever you feel comfortable with or is similar to something you have worked on before.
Good luck my fellow Flutter developer, choose wisely :P
You can use some event mechanism to notify MessageDao about an event in your app, e.g., AudioRecordingStartedEvent.
On MessageDao you subscribe on the event and stop the playing audio,
On ChatFooter you fire the event.
On pub.dev a lot of libraries that implement EventBus, e.g. event_bus_plus

Android difference between callback and listener

So in my understanding listener is usually used to trigger some class when some thing happened on particular place. (for example when we click the button we want to do some action).
On the other hand I see some places where callbacks are used to execute/enqueue some code in different place. (retrofit uses this to enqueue API calls)
What is the main difference between these 2?
In short, they are the same.
Really?
Yes. But there are some "theoretical" (and in some cases practical differences).
Concepts
Listener is a word that in Android, it's commonly associated with a View ClickListener or similar. Where there are methods like addxxxListener(...) etc.
A Callback is often heard in the context of "for this particular event" I supply a "callback" and I will be called back when something happens.
In practice, they are often just instances of some interface passed along.
In my limited experience (only about 10 years of Java/Android -now Kotlin as well-), the term is used interchangeably.
I normally think of a callback when I am expecting something to "call me back" when something happens, and a listener as something where I listen to an event but as you can see by reading this... they could be the same. :)
It's often mentioned that one could have multiple listeners, but one callback (but there's nothing enforcing this and I have seen all use cases you can think of where either term is used) "You can add multiple callbacks" is not uncommon, even though if there are "multiple" then it "must be a listener". In fact, if you go as far as Android's View, the method is view.setOnClickListener { }
So it's a Listener, but you can only set ONE. So the above rule about 1 callback, N listeners is already broken since the early days of Android.
In some cases though, the convention is more tied to the method name, rather than the class' name:
setXXXyyy(...) allows you to set "one" and only one yyy listener/callback.
addXXXyyy(...) allows you to add one or more (though not always, so read the documentation) yyy listener/callback.
An add is often (...but not always) accompanied by a removeXXXyyy(...) implying that if you keep/have a reference to a callback/listener you could remove it (and no longer be listening or be called back).
In the case of set, it's often expected that if needed you call set...(null) and pass that null to "remove" the sole listener/callback. (Views do this for you, you don't need to call it, but you can).
Anyway, don't quote me on this, but I'd argue they are the same. This is also more complicated when you involve other languages/frameworks/tools, where there's an even blurrier line.
In many instances, you will see callback used, but the method contains the word "Listener", and vice-verse, so don't get too crazy about it.
If you can, where you can, however, don't use either, just use Coroutines :)
For a concrete example of how both are used as the same thing...
Look at the Android View.setOnClickListener method:
/**
* Register a callback to be invoked when this view is clicked. If this view is not
* clickable, it becomes clickable.
*
* #param l The callback that will run
*
* #see #setClickable(boolean)
*/
public void setOnClickListener(#Nullable OnClickListener l) {
Notice something strange?
The method is called setOnClickListener yet the Javadocs say: "a callback..."
They are the same! Two ways of naming an interface. In general, Listener is also a callback and VICE VERSA!
for a type of event you can have many listeners , but one callback !
A callback is a procedure where you pass as an argument to another procedure. The procedure receiving the parameter can call it, or share it so some other procedures in the system can call it.
A listener watches for an event to be fired. For example, KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue, and so on.

View.Activate/Deactivate event listener registered multiple times

I have a simple Apache Flex view based application that runs on Android as follow:
<f:MyView xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/sparks"
activate="activateHandler(event)"
deactivate="deactivateHandler(event)"/>
I expect the activateHandler() should execute only once when the view is activated, however after I pop and then push the same view back the number of activateHandler() execution increased by how many times I did the pop and push operation. Why would this happen and how to force it to operate as expected (i.e only once)?
Expanding on #JileniBouguima's answer, changing activate to creationComplete will resolve this because of how those events work. Your expectation that activateHandler() executes only once is a little off; according to the Activate event documentation, activate fires
every time your application gains operating system focus and becomes active.
By contrast, creationComplete fires once per object, once the component is created.
I am not sure what code exactly is written in the handlers activateHandler and deactivateHandler but in Flex this is a standard practice to remove event listener if you do not need it any more. I am assuming that whenever you pop and push the same view it is adding and removing the listener. I can help you more if you share the handlers code.
Change activate to creationComplete.

Default key event handler in an Android Application

Is there a way in Android where an android application when active will catch and process all key events (and maybe touch events) before they are delivered to the actual view which is supposed to be handling it?
I know that we can have onKeyDown or similar method in Activity to handle the keyevent, but it is fired only if none of its child views handles it internally.
These view are usually ListView, GridView, ScrollView, etc..
I want to find a way that my keyHandler method is called before that keyEvent is delivered to these views.
Implementation in my keyHandler will be very simple. It will just play a tone upon each event, just like keypress tone, and then forward it to be handled the way it was meant to be by those views or Android framework.
Want to know if its possible beacuse I don't want to write onKeyListener to each and every view in every activity as I have lot of activities and lots of views and it will just become difficult to write the same code everywhere. If there is a way, i can implement that in BaseActivity and derive all my activities by that and go on my way of having default key handler.
I don’t try it myself but I think this one will help you: (just scroll a little bit down to the method mentioned in the text)
Input Event: Event Handlers - Activity.dispatchTouchEvent(MotionEvent)
Looks like this is the chance to catch events before they get to the window. Read the detailed Description here.

How to correctly use onVisibilityChanged(), onWindowVisibilityChanged(), onAttached/Detached()?

I've a custom class whose parent is SurfaceView. I have the class working correctly, drawing to the screen from its own thread etc. However I want to understand how the methods in the question title should be correctly handled.
For example, if my app is running (on a mobile phone) and a call is received, which method is called? Another example is if I implement a dialog box to be displayed if the user 'long-presses' on my custom SurfaceView, what method is called then? I assume the canvas is 'safe' to write to provided surfaceDestroyed() has not been called.
Basically I want to understand how I should handle eventualities as I've described (and possibly more?) and for what events each method is called.
on...-methods are called when something happened.
You probably don't have to implement them because the super class does the correct things in most cases.
If you put log in the methods in question you can see what happens / when they are called. You can also read the API doc and have a look at the source code to see what is done there.

Categories

Resources