I need to do some processing after the application enters in the background so I added this code to my app:
public override void DidEnterBackground (UIApplication application)
{
int taskid = 0;
taskid = application.BeginBackgroundTask(() => {
if(taskid != 0)
{
System.IO.File.WriteAllText(System.IO.Path.Combine(AppState.Current.User.Path, "blah"), "test");
application.EndBackgroundTask(taskid);
taskid = 0;
}
});
}
Then I monitored the filesystem (the emulator app) and the file never got written to the destination. Is there any reason why this is happening? Am I missing something?
The parameter of BeginBackgroundTask method is the expiration handler. It will be executed right before your background time expires. That is where you should only end the task and nothing else.
It is after the BeginBackgroundTask call where your background time starts.
Apple documentation.
Multitasking on iOS with MonoTouch.
Related
I'm integrating Agora with Unity, and we have a device selection screen for the user to select and test their devices before joining a call.
The problem I'm having is that Agora is not detecting device changes accordingly in runtime, which won't let me update my UI to reflect these changes.
void Start()
{
// get Agora engine, should be initialized already in the AgoraIOController component
agoraEngine = GetComponent<AgoraIOController>().GetAgoraEngine();
agoraEngine.OnAudioDeviceStateChanged += DeviceChangedHandler;
InitializeDeviceManager();
}
...
void DeviceChangedHandler(string deviceId, int deviceType, int deviceState)
{
devicesDirty = true;
onDevicesChanged.Invoke();
}
...
void RefreshDeviceList()
{
devices.Clear();
int audioDeviceCount = audioDeviceManager.GetAudioPlaybackDeviceCount();
if (audioDeviceCount == (int)ERROR_CODE.ERROR_NOT_INIT_ENGINE)
{
Debug.LogError("Agora engine not initialized, can't refresh devices");
return;
}
else if (audioDeviceCount < (int)ERROR_CODE.ERROR_OK)
{
Debug.LogError($"Unknown error while trying to get devices. Error code: {audioDeviceCount}");
return;
}
Debug.Log($"Found {audioDeviceCount} audio devices.");
for (int i = 0; i < audioDeviceCount; i++)
{
string deviceName = null;
string deviceId = null;
int result = audioDeviceManager.GetAudioPlaybackDevice(i, ref deviceName, ref deviceId);
if (result != (int)ERROR_CODE.ERROR_OK)
{
Debug.LogError("Error when trying to get audio device");
continue;
}
devices.Add(new AgoraDevice()
{
deviceId = deviceId,
deviceName = deviceName,
type = MEDIA_DEVICE_TYPE.AUDIO_RECORDING_DEVICE
});
}
}
If I connect a new microphone and restart the application, it's detected as expected, but if I connect a new device in runtime, I get the event for agoraEngine.OnAudioDeviceStateChanged but when I refresh the device list, the device count and device info is not being updated, so my UI is not showing the new state accordingly.
This happens if I have one mic and I connect a second one, or if I have two mics and I disconnect one. In either case Agora is not reflecting these changes after the devices changed event.
I also tried refreshing the device list in the next frame, or adding a button to manually refresh the list, to check if there was some delay in Agora for doing that update, but it's not happening.
Without this feature we're gonna have lots of issues with clients, connecting new devices in runtime happens all the time and we need to make this software robust and support these scenarios.
Any help is greatly appreciated!
EDIT:
Releasing and recreating the device manager helped, and the device list is updated, but this looks really weird and I don't think that the API should be used like this.
void DeviceChangedHandler(string deviceId, int deviceType, int deviceState)
{
devicesDirty = true;
audioDeviceManager.ReleaseAAudioRecordingDeviceManager();
audioDeviceManager.CreateAAudioRecordingDeviceManager();
onDevicesChanged.Invoke();
}
Since you are testing with mic plug/unplug, did you intend to call AudioPlaybackDeviceManager instead of AudioRecordingDeviceManager in your first part of the code?
in my game, when the player dies, a dying sound is played and once the sound is over, the scene is supposed to be reloaded when the user still has enough lives.
Before I had the sound, the play died instantly upon calling the death() function:
public static void Death()
{
AddCoinScript.coinCounter = 0;
LivesScript.livesCounter--;
if (LivesScript.livesCounter > -1)//to get 0 live
{
Debug.Log("TIMER");
var currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.name);
}
else
{
//TO DO GameOver
}
}
This worked like a charm.
But now I added a death sound to it. Unfortunately, unity doesnt provide an event handler for when the sound is done playing (I want the scene to be reloaded not instantly anymore, but after the death sound is done playing), so I have decided to take it upon myself to just build a timer. The timer fires right after the death sound is over. This is what this function has become:
public static void Death()
{
AddCoinScript.coinCounter = 0;
LivesScript.livesCounter--;
PlayDeathSound();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = aSDeath.clip.length * 1000;
timer.Start();
timer.Elapsed += delegate
{
timer.Stop();
if (LivesScript.livesCounter > -1)//to get 0 live
{
Debug.Log("TIMER");
var currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.name);
}
else
{
//TO DO GameOver
}
};
}
As you can see, to make sure the timer REALLY fires, I set up a "debug.Log("TIMER")" to see, if it really works. And guess what: it does. The debug now shows "TIMER" in its console. But you know what doesnt work anymore? The two lines of code right beneath that.
var currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.name);
It's the same exact lines that worked just before - but when fired from the timer, they just get ignored? How is this even possible?
When I change it all back, it works again. Only when the timer fires the two lines, they get ignored.
This is totally odd or am I missing something? Thank you!
Okay I am not an expert on C# and delegate but apparently it creates a separate thread and you can only use SceneManager.GetActiveScene on main thread.
Since i am not so sure about delegate i will offer an easier solution. You can use a coroutine since you know how much you have to wait like this:
public void Death()
{
StartCoroutine(DeathCoroutine());
}
IEnumerator DeathCoroutine()
{
AddCoinScript.coinCounter = 0;
LivesScript.livesCounter--;
PlayDeathSound();
// wait for duration of the clip than continue executing rest of the code
yield return new WaitForSeconds(aSDeath.clip.length);
if (LivesScript.livesCounter > -1)//to get 0 live
{
Debug.Log("TIMER");
var currentScene = SceneManager.GetActiveScene();
SceneManager.LoadScene(currentScene.name);
}
else
{
//TO DO GameOver
}
}
What about using a coroutine ? You just start it when the player dies, and yield while your sound is still playing.
My Codename One app features audio playback in the background when the user taps the screen. The audio I use is an mp3. Here is how I use the Media playback :
public static void playSound(boolean stop) {
sound.reset(); // The input stream needs to go back to the beginning
Media myClip = MediaManager.createMedia(sound, "audio/mp3", () -> {
// If there is no order to stop playback, we keep playing when it has completed (looping)
playSound(false);
});
if (!stop) {
myClip.play();
} else {
myClip.cleanup();
}
}
So hen the user taps the screen components change and I pass true to playSound method. On Android the current playback stops not on iOS with an iPhone 4.
Please note that when the app gets minimized (center button pressed) the playback stops (even if I don't call cleanup() on the Media which I do on Android to stop the playback when the app is minimized).
How can I stop the playback on iPhone ?
Any help appreciated,
#Shai pointed me to the right direction so here is the code finally used :
Media myClip = null;
public static void playSound(boolean stop) {
sound.reset(); // The input stream needs to go back to the beginning
/**
* If the media is playing we don't create it
* otherwise we would have several media in the wild
* that could not be stopped
*/
if (myClip == null || !myClip.isPlaying()) {
myClip = MediaManager.createMedia(sound, "audio/mp3", () -> {
// If there is no order to stop playback, we keep playing when it has completed (looping)
playSound(false);
});
}
if (!stop) {
myClip.play();
} else {
myClip.cleanup();
}
}
I wish to Show progress of a long running operation(process) in UI, so that the user can understand the status of the background job. This is the way I have implemented and I feel like the code is absurd. Below is my code
dialog.run(true,false, new IRunnableWithProgress() {
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Main process", 10);
for (int i = 0; i < 10; i++) {
if (monitor.isCanceled()) return;
monitor.subTask("Status message");
sleep(1000);
// worked increases the monitor, the values are added to the existing ones
monitor.worked(1);
if(i == 3) {
sleep(3000);
callMe();//calling a long running function
}
if(i == 9) {
monitor.subTask("finishing setup..... please wait ");
sleep(2000);
}
}
monitor.done();
}
});
Note: There is a sleep method somewhere in the code
here at i == 3 an operation/function is called that takes a minimum of 5 minutes, post execution of the function the progress continues.
I don't want the progress to be stopped while executing the function(long running operation) rather progress must be shown even while executing it.
can someone show the correct programming practices in showing progress
The reason your code feels absurd is that wrapping the long-running method in a IRunnableWithProgress.run() really does not add much in itself, there is no magic.
To make the ProgressMonitorDialog (or e.g. the related Job API) work for you, you need to change "callMe()" so it takes "IProgressMonitor monitor" as a parameter, and use that to listen for cancel-requests, and use it also for reporting progress.
To say the same again, using different wording: You need to recursively add "IProgressMonitor monitor" as a parameter to all long-running method calls. All long-running operations must be build with this (IProgressMonitor) in mind if any progress is to be reported and/or you want it to be cancelable.
In my application I'm using following coding pattern to vibrate my iPhone device
Include: AudioToolbox framework
Header File:
#import "AudioToolbox/AudioServices.h"
Code:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
My problem is that when I run my application it gets vibrate but only for second but I want that it will vibrate continuously until I will stop it.
How could it be possible?
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
There are numerous examples that show how to do this with a private CoreTelephony call: _CTServerConnectionSetVibratorState, but it's really not a sensible course of action since your app will get rejected for abusing the vibrate feature like that. Just don't do it.
Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.
iOS 5 has implemented Custom Vibrations mode. So in some cases variable vibration is acceptable. The only thing is unknown what library deals with that (pretty sure not CoreTelephony) and if it is open for developers. So keep on searching.
The above answers are good and you can do it in a simple way also.
You can use the recursive method calls.
func vibrateTheDeviceContinuously() throws {
// Added concurrent queue for next & Vibrate device
DispatchQueue.global(qos: .utility).async {
//Vibrate the device
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
self.incrementalCount += 1
usleep(800000) // if you don't want pause in between, remove this line.
do {
if let isKeepBuzzing = self.iShouldKeepBuzzing , isKeepBuzzing == true {
try self.vibrateTheDeviceContinuously()
}
else {
return
}
} catch {
//Exception handle
print("exception")
}
}
}
To stop the device vibration use the following line.
self.iShouldKeepBuzzing = false
ios swift