Android. How test duration execution of method? - android

I write unit test (JUnit, Espresso) for Android app.
And I want to test the duration of execution of any method in Activity. And my test must be fail if duration more than 1 second.
Is it possible in Android?

Here's an example:
private long durationTest() {
long timeBeforeExecution = System.currentTimeMillis();
someMethod();
return System.currentTimeMillis() - timeBeforeExecution; // difference in millis
}
private void someMethod() {
...
}

Yes, you can do that although it's hard to predict actual execution time as it depends on many factors. With JUnit you could do something like:
#Test(timeout=1000) //milliseconds
public void performanceTest() {
//my code
}
This test will fail if not executed under 1000ms and will pass for any other value.
With espresso test I believe you could adjust timeout rules but I don't see how that helps you in any way. UI test my depend on many things, how long it takes to "press" buttons, network response, other threads that have their own time management and depend on other factors. In any case check this:
Android Doc

long startTime = System.currentTimeMillis();
// here code to be time measured
Log.i ("Execution time ", "milliseconds : " + System.currentTimeMillis() - startTime);

Related

Change device time with cordova

is there any way to change an android device time from a cordova app?
I need to sync the device time with a server.
The app gets the server time from a webapi and if it's different from the device time i'd like to change the device time.
Thanks
You should not try to bend the whole device just to make your app work. What if the server-time is wrong? What if the user wants a different time?
We have the same needs for our app, and what we are doing is to run the app in server-time.
This is native Android in Java, but I think the idea should be clear and should also be possible in Cordova.
So we have this ServerTime class, and whenever we need the current time in our app, we do not use new Date() or System.currentTimeMillis(), but instead use ServerTime.now().
The class looks something like this (written from memory and simplified, make sure to test, maybe the diff-calculations should be + instead of - ...):
public static class ServerTime {
private static long diffMillis;
public static Date now() {
long millis = System.currentTimeMillis() - diffMillis;
return new Date(millis;
}
public static void update(long serverTimeMillis) {
diffMillis = System.currentTimeMillis() - serverTimeMillis;
}
}
The server provides the server's time with every response and additionally we poll the server-time every 15 minutes or so. Whenever we get the server's time, we call ServerTime.update(server's time in millis).

Alternative for SystemClock.sleep in Android Espresso

I am writing my test cases for my app however have come into some minor problems. Many of my test cases have SystemClock.Sleep calls in them, in order for the view to load all the data and display it on the screen. However the number of sleeps to do this has increasingly grown causing the time of these tests to be even longer.
Here is an example of one of these tests
#Test
public void testSearch() {
ExtensionForExpresso.signUp();
SystemClock.sleep(17000);
onView(withId(R.id.menu_offer_search)).check(matches(isDisplayed())).perform(click());
SystemClock.sleep(5000);
onView(withId(R.id.menu_search)).check(matches(isDisplayed())).perform(typeText("Pizza"));
SystemClock.sleep(17000);
onView(withId(R.id.searchSectionSeeAllButton)).check(matches(isDisplayed())).perform(click());
SystemClock.sleep(15000);
onView(withId(R.id.searchResultsRecyclerView)).check(matches(isDisplayed())).perform(RecyclerViewActions.actionOnItemAtPosition(1, click()));
}
Is there an alternative to sleep that will wait for view to appear? Or are there any methods or functions I can add in to reduce the amount of SystemClock.sleep calls?
First, try to disable animation on your device/emulator using adb shell or implement the Espresso Idling Resource in your Android project: http://matgom.com/tutorial/2016/02/21/IdlingResource.html
I would recommend you to implement an IdlingResource and Disable the system animations first. The easiest way to disable system animations is this.
There is no need to use the SystemClock.sleep() method. Instead you could implement a custom sleep method like this:
public void waitFor(int seconds) {
seconds = seconds < 0 ? 0 : seconds;
while (--seconds >= 0) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Then you could call it in your test like: waitFor(2); // 2 second wait

How to set up a timer for an android game ?

I want to programm a game for Android.
Play principle: The user should have a short time to choose the correct answer.
My problem is the combination between the input (choosing the answer) and the time (countdown). I tried to run a thread, but the thread isn't stoppable. So the user gives the answer, the next activity will be shown and after a while (when the "timer" becomes 0) the activity will be shown again.
How could I implement this in a correct way?
Should I use Thread, Handler, CountDownTimer ?
You can keep a running timer using this on init:
Timer updateTimer = new Timer("update");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 1000);
long startTime = System.currentTimeMillis();
Then in a Thread:
//Clock update
currentTime = System.currentTimeMillis() - startTime;
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
clock.setText(sdf.format(currentTime));
clock.invalidate();
You could stop the Thread with a boolean inside or outside as you please?
Okay, I don't know the specific libraries to use, and I haven't done any thread programming myself, but I would think of the program as a state machine. I hope it helps :/
Set up a boolean userHasAnswered = false.
Set up a specialized listener (e.g. touch listener for some button) for answers.
If the listener gets an appropriate response from the user, set userHasAnswered = true.
When question loads up, start the thread which counts down.
If user fails to give ans when the time reaches zero, just call loadNextQuestion().
In your thread, do periodic checks every few units of time to see if userHasAnswered == true, and if it is true, then call updateScore() and loadNextQuestion().
You may want to have a look at alarm manager

Trying to create an app with while loops

I'm a complete newb. I'm trying to port this simple program I made in class to an Android app. It's just suppose to print out " I love Computer Science!!" a certain amount. But I'm suspecting the while loop is causing my program to automatically force close. I've searched and found that I need to make a thread, but I can't find a similar situation.
Here's my onCreate method:
public void onClick(View v)
{
int number = 1;
int printed = 0;
int limit = 0;
int count = 0;
String countString;
second.setText("How much do you love Computer Science?");
countString = howMuchEditText.getText().toString();
count = Integer.valueOf(countString);
printed = count;
while ((count -1) >= limit)
{
third.setText(+number + " I love Computer Science!!");
count -= 1;
number ++;
}
fourth.setText("This printed " +printed + " times.");
}
});
}
}
Could anyone help me fix my force close?
Android only allows your application's handlers five seconds to execute before you'll get an "App not responding" message. Depending on the loop count, your onClick method could easily exceed that limit.
If you want to display an automatically updating counter, you will need to launch an asynchronous task that executes in the background.
Here is a quick tutorial on AsyncTask, but you will need to learn more about the fundamentals of the Android platform before it will make sense. Good luck!
To add to the previous answer, AsyncTask is not quite the answer either. This is because your modifications of the TextView cannot be done on a background thread—UI calls are only allowed on the main thread. To schedule periodic tasks on the UI thread, create yourself a Handler object, which has various post methods you can call to run tasks after a specified interval, or as soon as possible.

define android system sleep time interval

I'm writing an app which should shows on the screen if user wasn't interract with phone for some time. (I'm going to write a service which will show an activity after this time)
EDIT: Activity may not be open (that's why I must define non-interaction time in service)
Yes, there's this awesome method onUserInteraction() in the Activity class.
You can store the current time as a long in a variable and display the time difference.
onUserInteraction(){
latestInteractedTime = System.currentTimeMillis();
}
// In some method you want to probably display the time difference
String diff = "Time diff: " + (System.currentTimeMillis() - latestInteractedTime);
textView.setText(diff);

Categories

Resources