Resume player when incoming call - java-me

I want that after incoming call Track continues from point stop
I use this code:
public void playerUpdate(Player player, String event, Object data) {
if(event == PlayerListener.DEVICE_UNAVAILABLE) {
player.stop();
isPause = true;
}
if(event == PlayerListener.DEVICE_AVAILABLE) {
if(isPause == true) {
player.start();
}
}
}
But it isn't work. Track restarts.

instead of updating code in PlayerUpdate , please use a boolean value and when call gets interrupted automatically midlet goes to hideNotify() and save the mediaTime (is available) and resume player with showNotify() method and changing boolean value and starting player with player.start(); and player.setMediaTime(savedmTime);
here is piece of code.
protected void hideNotify() {
resume = false;
paintMessage = false;
mediaTime = player.getMediaTime();
}
// calls while resuming the application.
protected void showNotify() {
if (mediaTime != 0) {
if (pause) {
resume = false;
midlet.lcduiDisplay.callSerially(repainter);
mediaTime = player.getMediaTime();
pausePlayer();
} else {
resume = true;
long med = mediaTime / 1000;
med = med / 1000;
message = "Resuming...from " + med;
play(mediaTime);
}
}
}

Related

When app goes background the thread pause

I need your help.
I have a chronometer app very simply that show the time running.
I created a thread that count the time and update the UI.
When the app is in first plane, everything is fine.
When I press back buttom the app goes background but the Thread is paused for the system.
When I return to the App, the chronometer began to run again.
How I can do for maintenance the time running on background?
I will appreciate your hep.
Thanks,
Rodrigo.
private void cronometro(){
new Thread(new Runnable(){
#Override
public void run() {
while (true) {
if (isOn) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
mensaje_log = "Se produjo un error";
Log.d("Miapp",mensaje_log);
Escribirlog.escribir_eventos(mensaje_log);
mensaje_log = e.getMessage();
Escribirlog.escribir_eventos(mensaje_log);
Thread.currentThread().interrupt();
}
mili++;
if (mili == 999) {
seg++;
mili = 0;
saltos++;
if (saltos == 10) {
//escribe log cada 10 segundos
mensaje_log = "Corriendo...";
Log.d("Miapp",mensaje_log);
Escribirlog.escribir_eventos(mensaje_log);
saltos = 0;
}
}
if (seg == 59) {
minutos++;
seg = 0;
}
h.post(new Runnable() {
#Override
public void run() {
String m = "", s = "", mi = "";
if (mili < 10) {
m = "00" + mili;
} else if (mili < 100) {
m = "0" + mili;
} else {
m = "" + mili;
}
if (seg < 10) {
s = "0" + seg;
} else {
s = "" + seg;
}
if (minutos < 10) {
mi = "0" + minutos;
} else {
mi = "" + minutos;
}
m = m.substring(0,2); //toma los 2 primeros numeros de milisegundos
crono.setText(mi + ":" + s + ":" + m);
}
});
}
}
}
}).start();
}
In order to keep a task running in the background in flutter you will need to use a package, a one you can go with is https://pub.dev/packages/background_fetch, the way you going to use it like this:
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
bool isTimeout = task.timeout;
if (isTimeout) {
// This task has exceeded its allowed running-time.
// You must stop what you're doing and immediately .finish(taskId)
print("[BackgroundFetch] Headless task timed-out: $taskId");
BackgroundFetch.finish(taskId);
return;
}
print('[BackgroundFetch] Headless event received.');
// Do your work here...
BackgroundFetch.finish(taskId);
}
And then you will have to call it inside your main
void main() {
runApp(new MyApp());
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}
And finally call it when you need it to start fetching this way:
BackgroundFetch.start().then((int status) {
print('[BackgroundFetch] start success: $status');
}).catchError((e) {
print('[BackgroundFetch] start FAILURE: $e');
});
} else {
BackgroundFetch.stop().then((int status) {
print('[BackgroundFetch] stop success: $status');
});

Worker stop in the middle and not updating progress bar

I'm trying to load information with worker and using reportprogress to update progress bar until finshing, but the worker stop working and doesn't finish the for loop or continue after several minutes. I don't know what's the problem and I tried every post here I can find related to this problem and didn't get anything. I hope I can finally get an answer posting my problem here.
Here's the relevant code:
public class Class1
{
public BackgroundWorker unit_read_data_setting_Worker;
public Class1()
{
unit_read_data_setting_Worker = new BackgroundWorker();
unit_read_data_setting_Worker.WorkerReportsProgress = true;
unit_read_data_setting_Worker.WorkerSupportsCancellation = false;
unit_read_data_setting_Worker.DoWork += new DoWorkEventHandler(unit_read_data_setting);
unit_read_data_setting_Worker.ProgressChanged += new ProgressChangedEventHandler(_update_progress);
unit_read_data_setting_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
}
public void unit_read_data_setting(object sender = null, DoWorkEventArgs e = null)
{
lock (FamilyTreeViewModel.Lock_ParameterList)
{
ObservableCollection<Parameter_UC_ViewModel> _internal_parameter_list =
FamilyTreeViewModel.GetInstance.ParameterList;
if (FamilyTreeViewModel.GetInstance.SelectedUnitSetting != null)
{
if (_internal_parameter_list.Count > 0)
{
for (int i = 0; i < _internal_parameter_list.Count; i++)
{
int startValue = i * 100 / _internal_parameter_list.Count;
unit_read_data_setting_Worker.ReportProgress(startValue);
// do stuff related to the index
// when progress_bar at 76 value, the loop stoppes and cotinue after a minute
}
}
}
}
}
private void _update_progress(object sender, ProgressChangedEventArgs e)
{
FamilyTreeViewModel.GetInstance.Unit_read_data_setting_progress_bar = e.ProgressPercentage;
}
private void Completed(object sender, RunWorkerCompletedEventArgs e)
{
// never gets here but there's no error
}
}

Sound won't play at a specific time in unity

I am trying to make a sound play with the timer goes to 3, 2, 1.
My timer starts at ten and has a three second delay. If I use the following code:
if (tl.myCoolTimer == 10)
{
print("Play Sound");
myAudioSource.Play();
}
It plays the Beep over and over again until the game starts and the counter goes below 10.
If I use the code:
if (tl.myCoolTimer == 3)
{
print("Play Sound");
myAudioSource.Play();
}
It doesn't play the sound at all. It doesn't even print the print statement.
I literally only changed the number. I am not sure why this isn't working.
I have also tried setting it to 3f to see if it is a float issue.
Timer Scripts
This is the starting Timer. it counts down to 3 (then the game starts)
public Text startGameTimerText;
public float startGameTimer = 3;
public void Start ()
{
startGameTimerText = GetComponent<Text> ();
}
public void Update ()
{
startGameTimer -= Time.deltaTime;
startGameTimerText.text = startGameTimer.ToString ("f1");
if (startGameTimer < 0) {
GameObject.Find ("GameStartTimer").SetActive (false);
}
}
This is the Game Timer It starts at 10 and counts down to 0.
public StartGameTimer gt; //this is the script the other timer is on
public Text timerText;
public float myCoolTimer = 10;
public void Start ()
{
timerText = GetComponent<Text> ();
}
public void Update ()
{
if (gt.startGameTimer > 0) {
myCoolTimer = 10;
} else {
myCoolTimer -= Time.deltaTime;
timerText.text = myCoolTimer.ToString ("f1");
}
}
Thanks Joe for the help. Here was my final answer. I know it is hacked, but I haven't figured out the Invoke thing yet. When I set the into it kept playing the entire time it was at "3", so i need to make it play only once.
private AudioSource myAudioSource;
public bool isSoundPlayed;
void Start()
{
myAudioSource = GetComponent<AudioSource>();
isSoundPlayed = false;
}
void Update()
{
if((int)tl.myCoolTimer == 3)
{
if (isSoundPlayed == false)
{
myAudioSource.Play();
isSoundPlayed = true;
}
return;
}
if ((int)tl.myCoolTimer == 2)
{
if (isSoundPlayed == true)
{
myAudioSource.Play();
isSoundPlayed = false;
}
return;
}
if ((int)tl.myCoolTimer == 1)
{
if (isSoundPlayed == false)
{
myAudioSource.Play();
isSoundPlayed = true;
}
return;
}
}

Arguments and changing the value

A newbie, please excuse the terms and explanation.
I have a program that accepts arguments which are in seconds. This in turn runs a timer that shows on the form. I want to give the user the ability to pause the timer for a set amount of time. I am having difficulty in trying to add time after the user Clicks the button as the method that runs the timer and countdown I have a method that gets the parameters of the argument.
I would like to maybe just get the parameters/arguments globally and then use them in all the different methods or threads. I am trying to do this in c# and wpf.
Code below:
public partial class MainWindow : Window
{
//int TimeOutPeriod = Int32.Parse("3600");
//private Timer timer;
System.Timers.Timer timer = new System.Timers.Timer();
public MainWindow()
{
InitializeComponent();
//timer = new Timer(1000);
timer = new System.Timers.Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
string[] param = Environment.GetCommandLineArgs();
int TimeOutPeriod = Int32.Parse(param[1]);
ProgressBar1.Maximum = TimeOutPeriod;
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
string [] param = Environment.GetCommandLineArgs();
int TimeOutPeriod = Int32.Parse(param[1]);
int InYourFaceDisplay = Int32.Parse(param[2]);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
{
if (ProgressBar1.Value < TimeOutPeriod)
{
ProgressBar1.Value += 1;
RebootCDown.Content = "Machine will reboot in : " + (TimeOutPeriod - ProgressBar1.Value) + " Secs";
if ((TimeOutPeriod - ProgressBar1.Value) < InYourFaceDisplay)
{
this.Activate();
}
}
else
{
ShutDownWindows("0");
timer.Stop();
this.Close();
}
}));
}
private void SnoozeNow_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
ShowInTaskbar = false;
ni.Icon = new System.Drawing.Icon("C:\\temp\\RebootIco.ico");
ni.Visible = true;
ShowInTaskbar = false;
ni.ShowBalloonTip(5000, "Test App", "Notify icon is working! Right click to access the context menu.", System.Windows.Forms.ToolTipIcon.Info);
Task.Delay(10000);
ShowInTaskbar = true;
}
}

Video capturing issue

I want to create a LWUIT Image from the captured video. The problem is that the MediaException is raised when calling getSnapshot() :
private void showCamera() // called when clicking the "open camera" command
{
try
{
Player mPlayer;
VideoControl mVideoControl;
mPlayer = Manager.createPlayer("capture://video");
mPlayer.realize();
mVideoControl = (VideoControl) mPlayer.getControl("VideoControl");
Canvas canvas = new CameraCanvas(this, mVideoControl, mPlayer, getFirstAvailableRoot(), "ADC"+adcId); // adcId is "1"
isFromPositionnement = true; // static variable
javax.microedition.lcdui.Display.getDisplay(controler).setCurrent(canvas);
mPlayer.start();
} catch (IOException ex) {
handleException();
} catch (MediaException ex) {
handleException();
}
}
private String getFirstAvailableRoot()
{
short iter;
String root = "Phone:/";
iter = 0;
Enumeration drives = FileSystemRegistry.listRoots();
while(drives.hasMoreElements() && iter < 1) {
root = String.valueOf(drives.nextElement());
iter++;
}
return root;
}
Code in "CameraCanvas" :
public class CameraCanvas extends Canvas implements CommandListener
{
...
public CameraCanvas(Ecran form, VideoControl videoControl, Player pPlayer, String pRoot, String dossierPhoto)
{
...
mCaptureCommand = new Command("Capturer", Command.SCREEN, 1);
addCommand(mCaptureCommand);
setCommandListener(this);
...
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try
{
videoControl.setDisplayLocation(2, 2);
videoControl.setDisplaySize(width - 4, height - 4);
}
catch (MediaException me)
{
try
{
videoControl.setDisplayFullScreen(true);
}
catch (MediaException me2)
{}
}
videoControl.setVisible(true);
}
private void capture() // called when clicking the mCaptureCommand command
{
try
{
isPhotoCaptured = true;
rawImg = vidCtrl.getSnapshot(null); // this throws the exception
vidCtrl.setVisible(false);
vidCtrl = null;
mPlayer.close();
mPlayer = null;
repaint();
}
catch (MediaException me)
{
isPhotoCaptured = false;
rawImg = null;
vidCtrl.setVisible(false);
vidCtrl = null;
mPlayer.close();
mPlayer = null;
handleException("capture ");
}
}
}
So what may be the cause of the issue ?
MMAPI has the ability to create an image and you can easily turn it to a LWUIT image (which has a create image that accepts an object). However, for some reason the "geniuses" who came up with this API made image capture a restricted API to protect your privacy. So effectively you can't invoke this API without an operator/manufacturer signature.

Resources