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);
Related
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).
For now my app have a chat that comunicate via bluetooth with an OBD port in the car.
Now i want upgrade my project for real time information, so i want create a method that repeat some Array with a list of commands and repeat the sendMessage(message) every sec or 500 millisec (something for real time data).
There is some bestway to do that?
I have my Activity with 4 EditText for showing data and a Button with "start scan" and if pressed it becomes a "stop scan" and interrupt the infinite loop of commands.
In the same time i need to take back data and show results in the EditText.
EDIT
Or just use an AlarmManager?
EDIT 2
With this code not work properly because send only the first message after 5 sec and the second it lost...
How can i send all the commands into ArrayList one at a time every t millisec?
public void repeatCommand(){
for (final String command : commandArray){
final Handler handlerTimed = new Handler();
handlerTimed.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
sendMessage(command);
}
}, 5000);
}
/*String message = "010C\r";
sendMessage(message);*/
}
Sorry I didn't write android code for so long but I had your case so long ago.
You have to define a Service and start it in foreground with RETURN_STICKY and then write a handler with timer which execute your code per second (or what you like!). Then you can broadcast your result or how you want to communicate with your activity and use it.
Then start service and stop it with your button.
PS:
1. As far as I know alarmManager is not a good idea in this case.
Somehow you have to be sure that your Service will not be killed by 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);
Is there an easy possibility to measure the startup time an application takes? Similar questions are asking regarding self-made apps, but in this case I am talking about foreign apps to test and compare them. So far I couldn't find a simple app in the Play Store/iTunes App Store which just measures the time from the point where the user clicks the app icon to the state where it is fully loaded and can be worked with. I'd be thankful for any hints!
Put this code as your first line of code in the main activity :
Log.d("MyApp start time", "" + System.currentTimeMillis());
And after you consider the app loading ended put:
Log.d("MyApp end time", "" + System.currentTimeMillis());
Now just search the log for the info and you will the times over there
Try this tutorial or create separate application which will start your app (via Intent) and write to log (or save to file) current time (System.currentTimeMillis()) just before startActivity(intent).
Update:
In case foreign apps of You have create separate application which will start other app (via Intent) and write to log (or save to file or just store in variable) current time System.currentTimeMillis() just before startActivity(intent) like that:
Intent intent = getPackageManager().getLaunchIntentForPackage("<package of other app>");
if (intent!= null) {
Log.d(TAG, "Starting time: " + System.currentTimeMillis());
startActivity(intent);
}
(You can get other app package and main activity name this way) and than get launched apps list (or monitor logcat of them) like in that thread and when app appears in list or its log detected You can store timestamp of launched app. Difference between stored values indicates time for launch.
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