Handle device features in codename one - codenameone

for learning purposes, I am trying to write a simple sleep timer app. Purpose should be to have a picker, select a number of minutes and after that time, perform certain actions. Most importantly, activate flight mode and close all other applications to save the battery.
I have a custom picker and my runnable thread, which works fine:
#Override
public void run() {
while((System.currentTimeMillis() - startTime ) / 1000 < minutes){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("interrupted, go again.");
return;
}
}
System.out.println("Wait time is over, go to sleep.");
app.timeToSleep();
however, within "timeToSleep" I now want to do things like:
Device.setFlightmodeEnabled(true); or
TaskManager.killall();
How would I achieve something like that? I have not found anything so far, but maybe I have the wrong key words to look for.
Thanks and best regards

You can access some device features via API and some via native interfaces but I don't think setting a device to flightmode is technically possible without operator or Google authorization and that's only possible on Android...

Related

How to slow down the speed of execution?

I am using selenium web-driver with testing. I want to slow down the speed of execution.
Here is the sample code:
#Parameters({ "provider_name", "branch", "address", "clientId", "website", "UserName", "Password", "Dpid" })
public void addDematAccount(String provider_name, String branch, String address, String clientId, String website,
String UserName, String Password, String Dpid) {
driver.findElement(By.xpath("//a[contains(#href, '#/app/DematAccount/Add')]")).click();
setParameter(provider_name, branch, address, clientId, website, UserName, Password, Dpid);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
I have used driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); and Thread.sleep(2000); but not helping
There is no longer any way to control the speed of each "step" in Selenium WebDriver. At one time, there was a setSpeed() method on the Options interface (in the Java bindings; other bindings had similar constructs on their appropriately-named objects), but it was deprecated long, long ago. The theory behind this is that you should not need to a priori slow down every single step of your WebDriver code. If you need to wait for something to happen in the application you're automating, you should be using an implicit or explicit wait routine.
If you want to view it, and its too fast I would think you could maybe record your test being executed and then review it ?
See here : http://www.seleniummonster.com/boost-up-your-selenium-tests-with-video-recording-capability/
And here : http://unmesh.me/2012/01/13/recording-screencast-of-selenium-tests-in-java/
Here is some examples from the above link
public void startRecording() throws Exception
{
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
this.screenRecorder = new ScreenRecorder(gc,
new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,DepthKey, 24, FrameRateKey, Rational.valueOf(15),QualityKey, 1.0f,KeyFrameIntervalKey, 15 * 60),new Format(MediaTypeKey,MediaType.VIDEO, EncodingKey, "black",FrameRateKey, Rational.valueOf(30)),null);
this.screenRecorder.start();
}
public void stopRecording() throws Exception
{
this.screenRecorder.stop();
}
The whole purpose of automated tests ( in my opinion ) is so they can be run in the background without user interaction/without being viewed. Also, if you want to do as many tests as possible in a certain about of time speed and parallized testing is essential. If you want to view your tests being executed I think the above method would be good to ensure you don't ruin the performance of Selenium and view the execution when completed, you will have full control with the video to replay etc.
If you really want to execute your program slowly or even step by step, you can try the following approaches:
execute your program in debug mode one step at a time;
refactor your code into function blocks, only execute a block of code at one time, you will not see you code being executed slowly as in time, but it becomes easier for you to associate your codes with the results.

store data in every minute what should use Service, AsyncTask

I want to store data in database in every minute . For the same what should I use Service, AsyncTask or anything else. I go through various link which made me more confused .
I read the developer guide and came to know about getWritableDatabase
Database upgrade may take a long time, you should not call this method from the application main thread,
Then first I think I will use AsyncTask then about this
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
After that I think I can use Service then about Service
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
Here I am not able to understand what should I use to store data in database periodically. Please help me here as struck badly.
Thanks in advance
you cant do a lot work on the UI thread, so making database operations you could choose different approaches, few of them that I prefer to use are listed below;
Create a thread pool and execute each database operation via a thread, this reduces load on UI thread, also it never initializes lot of threads.
You can use services for updating the database operations. since services running on UI thread you cant write your operations in Services, so that you have to create a separate thread inside service method. or you can use Intent service directly since it is not working on UI Thread.
here is developer documentation on thread pool in android
and this is the documentation for IntentService
UPDATE
This will send an intent to your service every minute without using any processor time in your activity in between
Intent myIntent = new Intent(context, MyServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency= 60 * 1000; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);
Before that check if you really need a service to be started in each minute. or if you can have one service which checks for the data changes in each minute, starting new service would consume maybe more resources than checking itself.
UPDATE 2
private ping() {
// periodic action here.
scheduleNext();
}
private scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 60000);
}
int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return STICKY;
}
this is a simple example like that you can do

Has any one out there in the field used Dispatcher.Yield?

In "Lucian Wischik - Async Part 2 -- deep dive into the new language feature of VB/C#" for NDC 2012, the recommended use of Dispatcher.Yield is introduced to me. Does anyone out there have examples (and explanations) of how (and why) this call is used in the wild?
Well for example if you have a long running task but you still need to update your UI you can use Yield.
Yield gives you the ability to leave the current thread context and allow other code to run in the underlying context.
public async void MyButton_Click(object sender, RoutedEventArgs e)
{
for( int i=0; i < 10000; i++)
{
ProcessSomeStuff(i);
// await the Yield to ensure all waiting messages
// are processed before continuing
await Task.Yield();
}
}
In the example above you can process stuff async but calling Yield will allow events on the UI thread to execute also,
I love to use "await Dispatcher.Yield()" whenever I develop WPF applications.
It is easy to use and barely makes any problems in most cases.
The most useful case using Dispatcher.Yield() is when there is a small time of lag in a operation, which can not be bypassed by "Task", "Thread" etc.
For example, let's say that there is a command button which opens a new window or tab.
private void aButton_Click(object sender, RoutedEventArgs e)
{
// Do some ui stuff
// You can not use Task here at large.
}
What happens here is the whole application stopping, and the button UI remains pressed until the new window or tab opens. It is bad user experience and makes the apllicaiton seem so much slow.
and here is a code with a trick.
private async void aButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.Yield();
// Do some ui stuff
}
In here, your code works differently. Dispathcer will process other ui operations first before getting into the job. The button pressed motion will be released first and then a new window will come.
Application stopping will be same, but to users the application will be much smooth and fast. So it is usually a good idea to adopt Dispatcher.Yield() in your application.
In addition, Task.Yield() is different from Dispatcher.Yield(). Try two options and see the results.

How to get rid of the "click" sound at end of translation in Microsoft Translate API in Silverlight app

I am using the MS Translator to send back a WAV file of text to enable "talking" in my Silverlight 4 app.
However, at the end of every translation, there is a wierd click noise (it sounds like someone is turning a microphone on or off).
Here is an online Silverlight app which demonstrates the issue. Type something in and translate it (can be the same language) and listen to the end of the talking.
Is there anything I can do to get rid of this noise? I was thinking of reading the WAV file to 90% and then stopping it before the sound but I would like to understand technically why it's coming back with the noise and where the problem is so I can find the best solution for it.
UPDATE: After Brad's useful lead below it seems that the problem is in the WaveMediaStreamSource that converts the returned WAV into a format that Silverlight can use.
This is the same one mentioned/used in the online project here.
So... any idea how to get rid of the crackling sound when WaveMediaStreamSource converts it?
I'm not sure if this is helpful, but it seems that the click noise isn't in the WAV file itself.
I used Fiddler to dig out the response coming back from the server and saved that to a WAV file. Opening that in Audacity, I can clearly hear the translation to the end... no click.
So, that click might be the normal sound of the component in Silverlight stopping. However, I have a different theory.
The WAV file itself is sampled at 8kHz. That's kind of an oddball. I bet the click noise is an artifact of the sound card or software (silverlight/audio driver/windows itself, etc.) up-sampling to a more appropriate rate. This is testable. Try making a WAV file and use Fiddler or some other HTTP proxy tool to return your WAV instead of what was requested from the Microsoft server. See if your WAV (at 44.1kHz for example) has the same issue.
I had this same problem. I'm sure everyone does. Here is how I solved it.
Basically I added a marker to the stream that performed the callback 1 second before the audio was finished playing. That callback then fires a timer that is called 700ms later and that method stops the audio (about 300ms) before it's completed. I tried it without this timer and it was inconsistent. It seems like if you set a marker to fire 300ms before the end it wont always fire. Better to get it one second before and then run your own timer to cut it off when you are ready.
Here is the relevant code snippets. Hope it can help someone else. There are loads of other tricks to writing a smooth running audio player but this code should solve at least your clicking issue.
public void Page_Loaded(object sender, EventArgs args)
{
mediaElement.MediaOpened += new RoutedEventHandler(mediaElement_MediaOpened);
mediaElement.MarkerReached += new TimelineMarkerRoutedEventHandler(mediaElement_MarkerReached);
}
Timer t;
void mediaElement_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
{
// almost completed playing the file so lets stop before the annoying click is heard
t = new Timer(handleStopTimerDone, "", 700, 0);
}
public void handleStopTimerDone(object state)
{
// stop the audio playing
Stop();
}
private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
TimeSpan duration = mediaElement.NaturalDuration.TimeSpan;
TimelineMarker newMarker = new TimelineMarker();
newMarker.Time = new TimeSpan(duration.Ticks - 10000000);
while (mediaElement.Markers.Count > 0)
{
mediaElement.Markers.RemoveAt(0);
}
mediaElement.Markers.Add(newMarker);
}
public void Stop()
{
this.Dispatcher.BeginInvoke(delegate()
{
mediaElement.AutoPlay = false;
mediaElement.Stop();
mediaElement.Position = TimeSpan.FromSeconds(0);
if (memData != null)
{
WaveMediaStreamSource wavMss = new WaveMediaStreamSource(memData);
mediaElement.SetSource(wavMss);
}
});
}

Windows Phone 7 close application

Is there any possibility to programatically close Silverlight application on Windows Phone 7?
If you write an XNA Game, you will have access to an explicit Exit() method. If you are writing traditional Silverlight project, then NO, there is no way to programatically close your app. See also Peter Torr's Blog entry on Exiting Silverlight Apps in Windows Phone 7. There he also mentions the option of throwing an unhandled exception, which IMO is a terrible programing style.
An option you may try, is using the WP7 Navigation Service to programatically navigate back out of the application. Not sure if that would work though. Why do you need to Exit?
You can always call an exit by doing this at your landing page use this code on click of your application back button:
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
This will remove back entries from the stack, and you will press a back button it will close the application without any exception.
Short answer for Silverlight is No.
You should not provide a way to close the applicaiton. Closing the applicaiton should be the users choice and implemented by using the back button the appropriate number of times. This is also a marketplace requirement.
That said, a silverlight application will close if there is an unhandled exception. I have seen a few people try and create programmatic closing by throwing a custom error which is explicitly ignored in error handling. This can work but there is still the marketplace issue.
XNA applications can explictly call Exit().
Some good info here already. Adding to this..
The platform is fully capable of managing closure of apps. The more apps don't provide an exit, the quicker users will become accustomed to not thinking about app house keeping, and let the platform manage it.
The user will just navigate their device using start, back, etc.
If the user wants out of the current app to go do something else quickly - easy - they just hit start.
.Exit(), whilst available for xna, really isn't required anymore either. There was a cert requirement during CTP that games had to provide an exit button. This is now gone.
Non game apps never had the need to implement this.
The more this topic's discussed (and it really has been given a good run around the block), the more the indicators to me suggest there is no need to code an exit.
Update: For those thinking of an unhandled exception as a suitable way of closing an app intentionally or letting the app close due to subpar operating conditions, I would recommend reviewing the comments concerning Application Certification Requirements in this answer. Is there a way to programmatically quit my App? (Windows Phone 7)
Here is another solution.
If you have an error page that i.e. displays error to the end user you can use the
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
e.Cancel = true;
}
And you can instruct user to press start button to exit application.
Add a reference to Microsoft.Xna.Framework.Game, then call:
new Microsoft.Xna.Framework.Game().Exit();
private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
}
That works for me fine.
You can close the app using this statement
Application.Current.Terminate();
This worked perfectly on Windows phone 7
System.Reflection.Assembly asmb = System.Reflection.Assembly.Load("Microsoft.Xna.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553");
asmb = System.Reflection.Assembly.Load("Microsoft.Xna.Framework.Game, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553");
Type type = asmb.GetType("Microsoft.Xna.Framework.Game");
object obj = type.GetConstructor(new Type[] { }).Invoke(new object[] { });
type.GetMethod("Exit").Invoke(obj, new object[] { });
Link - source
My 2 pence worth, reasons for an exit
1) there is no interent connection the first time it is run and it needs to create an account on a web service somewhere to run.
2) You need to force an upgrade for the user, again when tied to a web service, you may discover a bug in your app, or have web service changes that mean the user needs to be forced to upgrade, at that point you will want to inform the user that they must upgrade and then exit the app.
Currently in my app I am forced to take the user to a form that says "they" must exit, and if they click back they are again forced back to this page. not very nice.
In Silverlight, I throw an un-handled exception when I have to exit the application. I know that this isn't the graceful method to handle this but it is still the most convenient and easiest solution.
I know that according to the guidelines there shouldn't be any un-handled exceptions in the code but I write why I am explicitly throwing an un-handled exception in the Exception Request document at the time of submission.
Till now this method has always worked and never failed me.
Easiest way to do this is to add a reference to Microsoft.Xna.Framework.Game, then add
using Microsoft.Xna.Framework.GamerServices; before namespace. Then we have a button in our Example.xaml with Click="quit_button". In out Example.xaml.cs we put this code inside our page-class:
private void quit_Click(object sender, EventArgs e)
{
new Microsoft.Xna.Framework.Game().Exit();
//This will close our app
}
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
//
}
}
e.Cancel = false;
}
else
{
//Stop page from navigating
e.Cancel = true;
}
Navigate to App.xaml.cs in your solution explorer and
add a static method to the App class
public static void Exit()
{
App.Current.Terminate();
}
so that you can call it anywhere from your application , as below
App.Exit();

Resources