We're trying to make a multipeer connection between two devices using MPC framework in libgdx game.
What generally we've done successfully:
Devices are connecting, session is establishing correctly.
After session is established nearBrowser and nearAdvertiser stop
doing their stuff.
Then we do transition to the game scene. In the new scene one device
can send a message to another.
DidReceiveData method from Session Delegate is called and there
we've got right messages for both devices.
After this we send to libgdx message for updating content (in main
gdx thread).
BUT after a while when some device received data it immediately crashes. Sometimes it happens on 10th receiving, sometimes after 200th. Crash appears only on the device that received message. It doesn't matter how long they are connected. Crash appears after all methods have done their work with data. So we don't know where exactly error happens.
// MCSession delegate method
public void didReceiveData(MCSession session, NSData data, MCPeerID peerID) {
//there we make userInfoData
//
DispatchQueue.getMainQueue().async(new Runnable() {
#Override
public void run() {
NSNotificationCenter.getDefaultCenter().postNotification(new NSString("didReceiveData"), null, userInfoData);
}
});
}
// Register observer in NSNotificationCenter
// NSNotificationCenter.getDefaultCenter().addObserver(this, Selector.register("updateDataWithNotification:"), new NSString("didReceiveData"), null);
// This method is called when device has received new data
#Method
private void updateDataWithNotification(NSNotification notification){
userInfoDict = notification.getUserInfo();
data = (NSData) userInfoDict.get(new NSString("data"));
strBytes = new String(data.getBytes());
// i'm not sure this Gdx.app.postRunnable is really needed
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
SBGlobalMessanger.getInstance().readBluetoothMessage(BluetoothData.RC_MESSAGE, strBytes);
}
});
}
The questions are:
Where is the bug? And how can we fix it?
The problem was in robovm plugin. In debug mode it made build that crushed. After making release build bug disappeared. The thing i have learned after working with robovm + libgdx is if you have strange bug just make a release build. It seems that this kind of bugs was eliminated with the last release of robovm 1.3 (i haven't try it out yet).
Related
I am trying to create a Xamarin.Forms app that will run on both iOS and Android. Eventually I need instances of the app to communicate with each other via Bluetooth, but I'm stuck on getting the iOS side to do anything with Bluetooth. I originally tried to work with Plugin.BluetoothLE and Plugin.BLE, but after a week and a half I was not able to get advertising or scanning to work on either OS with either plugin, so I decided to try implementing simple Bluetooth interaction using the .NET wrappers of the platform APIs, which at least are well documented. I did get scanning to work fine on the Android side. With iOS, though, what I have right now builds just fine, and runs on my iPad without errors, but the DiscoveredPeripheral handler is never called, even though the iPad is just a few inches from the Android tablet and presumably should be able to see the same devices. I have verified this by setting a breakpoint in that method, which is never reached; and when I open the Bluetooth Settings on the iPad to make it discoverable the app version on the Android tablet can see it, so I don't think it's an iPad hardware issue.
It seems obvious that there is simply some part of the process I don't know to do, but it's not obvious (to me) where else to look to find out what it is. Here is the code for the class that interacts with the CBCentralManager (as far as I understand from what I've read, this should include everything necessary to return a list of peripherals):
using MyBluetoothApp.Shared; // for the interfaces and constants
using CoreBluetooth;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(MyBluetoothApp.iOS.PeripheralScanner))]
namespace MyBluetoothApp.iOS
{
public class PeripheralScanner : IPeripheralScanner
{
private readonly CBCentralManager manager;
private List<IPeripheral> foundPeripherals;
public PeripheralScanner()
{
this.foundPeripherals = new List<IPeripheral>();
this.manager = new CBCentralManager();
this.manager.DiscoveredPeripheral += this.DiscoveredPeripheral;
this.manager.UpdatedState += this.UpdatedState;
}
public async Task<List<IPeripheral>> ScanForService(string serviceUuid)
{
return await this.ScanForService(serviceUuid, BluetoothConstants.DEFAULT_SCAN_TIMEOUT);
}
public async Task<List<IPeripheral>> ScanForService(string serviceUuid, int duration)
{
CBUUID uuid = CBUUID.FromString(serviceUuid);
//this.manager.ScanForPeripherals(uuid);
this.manager.ScanForPeripherals((CBUUID)null); // For now I'd be happy to see ANY peripherals
await Task.Delay(duration);
this.manager.StopScan();
return this.foundPeripherals;
}
private void DiscoveredPeripheral(object sender, CBDiscoveredPeripheralEventArgs args)
{
this.foundPeripherals.Add(new CPeripheral(args.Peripheral));
}
private void UpdatedState(object sender, EventArgs args)
{
CBCentralManagerState state = ((CBCentralManager)sender).State;
if (CBCentralManagerState.PoweredOn != state)
{
throw new Exception(state.ToString());
}
}
}
}
Can anyone point me in the direction of understanding what I'm missing?
EDIT: O...K, I've discovered quite by accident that if I do this in the shared code:
IPeripheralScanner scanner = DependencyService.Get<IPeripheralScanner>();
List<IPeripheral> foundPeripherals = await scanner.ScanForService(BluetoothConstants.VITL_SERVICE_UUID);
twice in a row, it works the second time. I feel both more hopeful and much more confused.
The underlying problem was that in the first instantiation of PeripheralScanner, ScanForService was being called before State was updated. I tried many ways of waiting for that event to be raised so I could be sure the state was PoweredOn, but nothing seemed to work; polling loops simply never reached the desired state, but if I threw an Exception in the UpdatedState handler it was thrown within milliseconds of launch and the state at that time was always PoweredOn. (Breakpoints in that handler caused the debugging to freeze with the output Resolved pending breakpoint, which not even the VS team seems to be able to explain).
Reading some of the Apple developer blogs I found that this situation is most often avoided by having the desired action occur within the UpdatedState handler. It finally soaked into my thick head that I was never seeing any effects from that handler running because the event was being raised and handled on a different thread. I really need to pass the service UUID to the scanning logic, and to interact with a generic List that I can return from ScanForService, so just moving it all to the handler didn't seem like a promising direction. So I created a singleton for flagging the state:
internal sealed class ManagerState // .NET makes singletons easy - Lazy<T> FTW
{
private static readonly Lazy<ManagerState> lazy = new Lazy<ManagerState>(() => new ManagerState());
internal static ManagerState Instance { get { return ManagerState.lazy.Value; } }
internal bool IsPoweredOn { get; set; }
private ManagerState()
{
this.IsPoweredOn = false;
}
}
and update it in the handler:
private void updatedState(object sender, EventArgs args)
{
ManagerState.Instance.IsPoweredOn = CBCentralManagerState.PoweredOn == ((CBCentralManager) sender).State;
}
then poll that at the beginning of ScanForService (in a separate thread each time because, again, I will not see the updates in my base thread):
while (false == await Task.Run(() => ManagerState.Instance.IsPoweredOn)) { }
I'm not at all sure this is the best solution, but it does work, at least in my case. I guess I could move the logic to the handler and create a fancier singleton class for moving all the state back and forth, but that doesn't feel as good to me.
I'm wondering if anyone has figured out a way to properly handle timeouts in the JavaFX 8 (jdk 1.8.0_31) WebView. The problem is the following:
Consider you have an instance of WebView and you tell it to load a specific URL. Furthermore, you want to process the document once it's loaded, so you attach a listener to the stateProperty of the LoadWorker of the WebEngine powering the web view. However, a certain website times out during loading, which causes the stateProperty to transition into Worker.State.RUNNING and remain stuck there.
The web engine is then completely stuck. I want to implement a system that detects a timeout and cancels the load. To that end, I was thinking of adding a listener to the progressProperty and using some form of Timer. The idea is the following:
We start a load request on the web view. A timeout timer starts running immediately. On every progress update, the timer is reset. If the progress reaches 100%, the timer is invalidated and stopped. However, if the timer finishes (because there are no progress updates in a certain time frame we assume a time out), the load request is cancelled and an error is thrown.
Does anyone know the best way to implement this?
Kind regards
UPDATE
I've produced a code snippet with behavior described in the question. The only thing still troubling me is that I can't cancel the LoadWorker: calling LoadWorker#cancel hangs (the function never returns).
public class TimeOutWebEngine implements Runnable{
private final WebEngine engine = new WebEngine();
private ScheduledExecutorService exec;
private ScheduledFuture<?> future;
private long timeOutPeriod;
private TimeUnit timeOutTimeUnit;
public TimeOutWebEngine() {
engine.getLoadWorker().progressProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
if (future != null) future.cancel(false);
if (newValue.doubleValue() < 1.0) scheduleTimer();
else cleanUp();
});
}
public void load(String s, long timeOutPeriod, TimeUnit timeOutTimeUnit){
this.timeOutPeriod = timeOutPeriod;
this.timeOutTimeUnit = timeOutTimeUnit;
exec = Executors.newSingleThreadScheduledExecutor();
engine.load(s);
}
private void scheduleTimer(){
future = exec.schedule(TimeOutWebEngine.this, timeOutPeriod, timeOutTimeUnit);
}
private void cleanUp(){
future = null;
exec.shutdownNow();
}
#Override
public void run() {
System.err.println("TIMED OUT");
// This function call stalls...
// engine.getLoadWorker().cancel();
cleanUp();
}
}
I don't think that you can handle timeouts properly now. Looks at this method. As you can see it has hardcoded value for setReadTimeout method. Is it mean that SocketTimeoutException exception will be raised after one hour of loading site. And state will be changed to FAILED only after that event.
So, you have only one way now: try to hack this problem use Timers as you described above.
P.S.
Try to create issue in JavaFX issue tracker. May be anyone fixed it after 5 years...
I have the same problem and used a simple PauseTransition. Same behavior, not so complicated. =)
I am trying to figure out a way of timing out a connection to my streaming http source if it becomes unavailable. I do have checks in place which verify if I'm connected to the internet, either WIFI or Data. I did find some example using a Handler and I got to the point where it actually times out, but it doesn't stop the actual service which is in a different class. This causes a ANR in emulator. Any suggestions or different approaches on how this issue can be handled? Thank you for your time !
public Runnable mUpdateTimeTask = new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "Running Thread", Toast.LENGTH_LONG).show();
if (RadioService.isMusicActive()==false){
stopPlaying();
}
}
};
private void stopPlaying() {
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
stopService(new Intent(this, RadioService.class));//
}
if (v == buttonPlay) {
startPlaying();
mHandler.postDelayed(mUpdateTimeTask, 5000);}
After playing more with it and some minor modifications, this code worked the way I expected. Maybe it will help somebody else down the road.
I can successfully register my app for push notifications:
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(
UIRemoteNotificationType.Alert
| UIRemoteNotificationType.Badge
| UIRemoteNotificationType.Sound);
But whenever I execute this, my UI hangs for usually 2-3 seconds. Even if I have it early in the app lifecycle as recommended (e.g., even WillFinishLaunching) my UI still hangs once my first ViewController loads.
My first thought was to execute the registration in a separate thread, but MonoTouch prevents this:
// From MonoTouch.UIKit
public virtual void RegisterForRemoteNotificationTypes(UIRemoteNotificationType types)
{
UIApplication.EnsureUIThread();
My next thought was to at least pop up a UIAlertView box to let the user know something's going on, but for some reason it didn't display until after the registration took place, resulting in the UIAlertView opening and immediately closing!
modalPopup = new UIAlertView("Working", "The application is loading...", null, null);
modalPopup.Show();
// It doesn't show here!
RegisterForRemoteNotificationTypes();
// It shows here!
modalPopup.DismissWithClickedButtonIndex(0, true);
How can I either
Stop the push notification registration from tying up my UI thread
cover up the UI freeze?
Did you override public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
or
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
I've had similar problem where within Registered... function, I called a web service to upload the device token. But the web call wasn't within another thread so it caused to freezes UI.
I am trying to establish a PIM listener that will update a MainScreen where all the contacts of the phone are listed.
What I am doing is the following:
I am loading for one time only a form called ContactsForm and I am storing it into the RuntimeStore
I created a PIMListListener to listen for all the changes that will occur in the address book.
When a contact is added, I am adding it to the contactsForm successfully
When a contact is removed, I am facing a big problem deleting it :S!!!
I am getting this exeption: "IllegalArgumentException"; this exception's text is : UiEngine accessed without holding the event lock. I know such errors and I know how to resolve them. So I used the following code:
UiApplication.getUiApplication().invokeLater( new Runnable() { public void run() {
synchronized(UiApplication.getEventLock()) {
uiContacts.vm.delete(uiContacts.vm.getField(j));
}
}});
This should resolve the problem. But I keep getting this error again and again. How to resolve this?
Listeners, like the PIMListListener, do not receive their callbacks in the same Application context as your UiApplication. So, in your code, UiApplication.getUiApplication() doesn't really work the way you'd expect it to.
The best thing to do would be to store a reference to your UiApplication in a place where the callback can reach it (during initialization of the UiApplication, perhaps), and then replace UiApplication.getUiApplication().invokeLater(...) with myUiApp.invokeLater(...), where myUiApp is the reference to your UiApplication which you stored earlier.