I developed an android turn based game and so far I can make the first move but when I want the user would wait for the second player to play the app crashes.
What I tried to do is when the player finishes his move I call a function like this:
public void TheThread()
{
boolean fy=false;
while(!fy)
{
if(CheckMove2())
fy=true;
}
}
The checkmove2 function connects the parse table and check if is there a turn and return boolean.
I beleive this is not the right way to do it,thanks for your help.
Edit:
ChecKmove2() function:
private boolean CheckMove2() {
fx=false;
ParseQuery query = new ParseQuery("serverturn");
query.whereEqualTo("Receiver", Sender);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject updatePO, ParseException ParseError) {
if(ParseError == null){
fx=true;
String objID;
x=updatePO.getInt("x");
y=updatePO.getInt("y");
try {
updatePO.delete();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
///here comes the game algorithm.
if(fx)
return true;
return false;
}
Edit: the app not crashes its just stop and alert: "The app is not responding" and then asks if I want to wait or close the app.The checkmove function works perfectly I checked it with other devices,the problem is to use this checkmove function in a while loop so the user would wait for the opponent turn.
Your application is crashing because in that scenario you've caused an endless loop (if there are no other moves waiting). So the OS will, most likely force close your application because it thinks its become unresponsive.
What you're better off doing is this:
Create a background service with an AyncTask to check for other players moves at specific intervals (10 - 15 mins maybe?)
Once a move is found. Alert the player to it by using a Notification which would link to your app via an Intent
As a side note, you should always use background threads/async tasks etc to talk to networks.
On your place i would do next:
In parse cloudCode afterSave or beforeSave of the object you are waiting for, send a socket message to your app when the needed object is updated. For example using pubnub.com
I think this is a decent solution, but running some loopy checking logic seemes so unprofessional.
In general it works like this:
two players subscribe to a channel
when one finishes move, from cloud code send a message to this
channel
catch it in your app.
The message can trigger update from parse or can contain the needed data itself.
Related
I want to know whether the call is disconnected or continued, and based on that I want to perform an action in the application.
Can anyone tell me how to check if the phone call is disconnected or not?
along with that I also want to know if it is received by the end-user or not
any kind of help will be appreciated.
thank you
I think you should take the steps I list below:
One line of code can make a phone call
Wait for any in-flight phone
Calls Watch everything that happens on the phone during a single Call or all
calls.
Keep track of the length of calls, errors, and
call drops.
Now let’s start
Install the plugin
Flutter_phone_state: ^0.5.8
Initiate a call
It is best to make calls from your app whenever you can. This is the best way to find where the call came from.
final phoneCall = FlutterPhoneState.makePhoneCall("480-555-1234");
The truth about a call comes from a PhoneCall object.
showCallInfo(PhoneCall phoneCall) {
print(phoneCall.status);
print(phoneCall.isComplete);
print(phoneCall.events);
}
PhoneCall.events can be read as a stream, and when the call is over, the plugin will gracefully close the stream. The plugin keeps an eye on all calls in progress and will eventually force any call to time out.
watchEvents(PhoneCall phoneCall) {
phoneCall.eventStream.forEach((PhoneCallEvent event) {
print("Event $event");
});
print("Call is complete");
}
You could also just wait until the call is over.
waitForCompletion(PhoneCall phoneCall) async {
await phoneCall.done;
print("Call is completed");
}
Accessing in-flight calls
In-flight calls can be accessed like this:
final `activeCalls = FutterPhoneState.activeCalls;`
Note that activeCalls is a copy of the calls at the time you called it. This copy cannot be changed. It won't be updated on its own.
Watching all events
You can watch all the events instead of just focusing on one call. We recommend using “FlutterPhoneState.phoneCallEventStream” because it includes our own tracking logic, call timeouts, failures, etc.
watchAllPhoneCallEvents() {
FlutterPhoneState.phoneCallEvents.forEach((PhoneCallEvent event) {
final phoneCall = event.call;
print("Got an event $event");
});
print("That loop ^^ won't end");
}
You can sign up to get the raw events if you want to. Keep in mind that there are only so many of these events.
watchAllRawEvents() {
FlutterPhoneState.rawPhoneEvent.forEach((RawPhoneEvent event) {
final phoneCall = event.call;
print("Got an event $event");
});
print("That loop ^^ won't end");
Do you have any ideas on how to solve in an android long time of waiting on server response?
I am making a request to the API saving profile.
This request is fast
But the server is processing it rather long 10sec to 3min (like scanning cheap flight on some tickets sites)
After the response, I need to redirect the user to a confirmation screen or home screen of the app.
I solved this by setting the longer timeout to 45 sec and then always redirecting to confirmation + alert that it takes longer.
On the home screen, I am displaying "Processing..." label until the server finishes
But this solution has some problems like:
what about user going out by home button if it takes longer, or switching applications, and if just display goes to sleep while untouched more than 30sec? Then activity/fragment is recreated and response seems to not arrive.
I consider adding push notification when processing is done this could help a little. Is there any way to solve such an issue? Maybe some background Service? But isn't Android Services deprecated? I think only Foreground Services are valid to use, or maybe new WorkManagers (but this doesn't seem to fit this scenario). And how from then wakeup screen and move it to the next page.
Code sample:
// Fragment
viewModel.saveData(data)
// View Model
fun saveData(data: Data) : LiveData<Resource<DataResponse>> {
_dataEvent.postValue(Event(Resource.loading(null)))
val apiSource = dataRepo.saveData(data)
_dataEvent.addSource(apiSource) { resource ->
_dataEvent.removeSource(apiSource)
val resource = resource ?: Resource.error(null, null)
_dataEvent.postValue(Event(resource))
}
return apiSource
}
// Observing Data Event
viewModel.dataEvent.observe(this,
Observer { event ->
if(event?.peekContent()?.status == Resource.Status.LOADING) {
showProgressAlert(context)
event.getContentIfNotHandled() // consume loading event
}
val resource = event?.getContentIfNotHandled()
if(resource != null) {
hideProgressAlert()
if (resource.status == Resource.Status.SUCCESS) {
showSuccessAlert(context)
navigateToConfirmPage()
} else if (resource.status == Resource.Status.ERROR) {
if (throwable is SocketTimeoutException) {
showTimeoutAlert(context)
navigateToConfirmPage()
} else {
showErrorAlert(context)
}
}
}
If this request is taking a long time then you should perform it in a background thread, Since android oreo background services became very restricted if you want to implement it you can use JobIntentService or JobScheduler or make it a ForegroundService but in this case you will have to show a notification to the user while the service is running, You can read more about it here https://developer.android.com/about/versions/oreo/background
Another approach is to use RXjava which handles threading and perform background services very smoothly
I am developing an application for my friend who is in sales, this application will make phone calls one after another, as soon as one phone call gets disconnected, it will automatically make call to another number from the list. This list can be read from and xml data source or json or mongodb or even from excel sheet.
This could be an ios app that reads data from an end point and stores them and can initiate the call at any point and it wont stop until all the calls are made.
Next call will be made only after the first call has been finished.
I am thinking about using node based web app using google voice to trigger the chain.
I've no experience with ios / android apis but Im willing to work on that if it's a viable thing on that platform.
Note: what we're trying to avoid is whole process of
looking up the phone number.
touch hangup and then click for another phone number.
It should self trigger the next call as soon as current call gets disconnected.
Also we're trying to avoid any paid services like twillo.
Thanks in advance :)
for IOS, you could use CTCallCenter
self.callCenter = [[CTCallCenter alloc] init];
self.callCenter.callEventHandler = ^(CTCall *call){
if ([call.callState isEqualToString: CTCallStateConnected])
{
//NSLog(#"call stopped");
}
else if ([call.callState isEqualToString: CTCallStateDialing])
{
}
else if ([call.callState isEqualToString: CTCallStateDisconnected])
{
//NSLog(#"call played");
}
else if ([call.callState isEqualToString: CTCallStateIncoming])
{
}
};
Download phone list, loop inside phone list, make a call, listening for CTCallCenter and appdelegate's Event, detect user have finish last call, our app active again, then make the next call.
Or you can try in Demo here !
I have being upgrading an application to use the new Mobile Android GNSK but I have noticed that using the new MusicID-Stream is a little bit tricky. If the "identifyAlbumAsync" method get executed before the "audioProcessStart" method(since this need to be executed in a different thread), the application just crashes. In the Gracenote Demo application, the "audioProcessStart" method is continuously running so there is no need to synchronize its execution with the "identifyAlbumAsync" method call. Is it the way it is supposed to be used? It will be convenient if the application didn't crashed at least when the methods are not executed in order. Also in our application, we don't want to have the "audioProcessStart" method continuously like it is done in the demo application. We only want to run the "audioProcessStart" method when the user request identification and when the song playing gets identified , we want to stop the audio processing by calling "audioProcessStop". Is there an easy way to do this? Right now, we are getting the Thread where "identifyAlbumAsync" is running to sleep for 2 seconds in order to make sure that the Thread where the "audioProcessStart" method is supposed to run has time to get executed. Thank you in advance for your prompt response
In the upcoming 1.2 release, IGnMusicIdStreamEvents includes a callback that signals audio-processing has started, and an ID can be synced with this, e.g.:
#Override
public void musicIdStreamProcessingStatusEvent( GnMusicIdStreamProcessingStatus status, IGnCancellable canceller ) {
if (GnMusicIdStreamProcessingStatus.kStatusProcessingAudioStarted.compareTo(status) == 0) {
try {
gnMusicIdStream.identifyAlbumAsync();
} catch (GnException e) { }
}
}
Thanks for the feedback, you're right about this issue. Unfortunately right now sleeping is the best solution. But we are adding support for an explicit sync event in an upcoming release, please stay tuned.
I am currently trying to integrate a live search functionality in android. I use a customized Autocomplete widget. The widget itself provides me with a threshold to only start a query after a certain amount of characters have been typed in. But what I also want is that a query only starts, say if a user has stopped typing for 2 seconds.
As I load my contents with a AsyncTask I tried blocking the doInBackground function by calling Thread.sleep() right at the beginning. If the user would then continue typing the program would look after an existing task, cancel it and start a new one. This was my idea. But it doesn't quite work the way I expected. Sometimes it sends out queries even if the user is still typing, sometimes queries are canceled after the users stopped typing.
Do you have any ideas on this or maybe a better way to solve this?
Here are the code snippets:
1. The function that is called on text changes:
public void afterTextChanged(Editable s) {
if(mWidget.enoughToFilter()) {
if(mTask != null && mTask.getStatus() != Status.FINISHED) {
mTask.cancel(true);
}
mTask = new KeywordSearchLoader(mActivity,
mItems);
mTask.execute(s.toString());
}
}
2. doInBrackground
try {
Thread.sleep(Properties.ASYNC_SEARCH_DELAY);
} catch (InterruptedException e) {
Log.e(TAG, "the process was interrupted while sleeping");
Log.w(TAG, e);
}
Thanks
Phil
Create a Handler and use .postDelayed(..) to run a background task after some delay.
If user presses the key then call handler.removeCallback(..) and then again .postDelayed(..) to add a new delayed callback.