[Q] How do i get the Time an App is currently Running? - Java for Android App Development

Hallo everbody,
im writing a background service to get informations like the time an active app (not my app) is running.
With this information i can show the user a list of the most used apps depending on the time.
The methods of the ActivityManager-class are useless, because the received informations aren't reliable.
So i thought, because the Android-System is based on a Linux-Kernel, i can use the internal structure to get these informations.
So i read out the pseudo proc-filesystem to get the process informations and for the 2nd time i thought
thats the right place for me to get what i want.
I read out the stat-file in every single process-directory to get the starttime(in clock_ticks) of the process.
I dynamic calculate the HZ USER_HZ value and use it to get the real starttime but this time never changes.
It's more like a timestamp of the first start on the system after boot.
The user-code-time and kernel-code-time seems to be too short and the values are updated too irregular.
So i just got a time value, that tells me the time when the app was first started after system boot
but i want a timestamp or anything else i can get from a currently running app to calculate the time this app is active.
Long life services and background services are not my goal.
Now i'm here because i don't know if i just miscalculate the values from this pseudo filesystem or
if i'm absolutely wrong where i get my informations from.
My Questions:
1. Do i read the wrong values files filesystem (if yes, where can i find these informations in the system structures)
2. Do i misunderstand some of the values i read out
3. Why do the files in the process directories become updated so irregular or once in a lifetime (just if im in the right filesystemfile)
I hope u can help me. *-*

Well, interesting approaches. :good:
The only way I see is running a background service and storing the launch time yourself.
I'm sorry but I don't know the answers to your questions.

You could
a) use su to get the active process list
b) get to /proc/??? folder (where ??? is the apppropriate process you enquire, for example /proc/80/)
c) get the /proc/80/sched text file and look for exec_runtime or vruntime or what ever works for you

carbonpeople said:
You could
a) use su to get the active process list
b) get to /proc/??? folder (where ??? is the apppropriate process you enquire, for example /proc/80/)
c) get the /proc/80/sched text file and look for exec_runtime or vruntime or what ever works for you
Click to expand...
Click to collapse
Oh, getting the currently running tasks can even be done much easier and doesn't require root. This is what I use:
Code:
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processInfoList = am.getRunningAppProcesses();

carbonpeople said:
You could
a) use su to get the active process list
b) get to /proc/??? folder (where ??? is the apppropriate process you enquire, for example /proc/80/)
c) get the /proc/80/sched text file and look for exec_runtime or vruntime or what ever works for you
Click to expand...
Click to collapse
that seems to be exactly what i need!
but there are the next questions:
what is the unit of the "se.sum_exec_runtime"-field? is it in nano-secs?
what does the point do in the value? does it indicates a floating-point value?
im kinda confused and didnt really find something meaningful about the unit (*-*)
and im not very handy with the kernel code from "lxr.linux.no"

nikwen said:
Oh, getting the currently running tasks can even be done much easier and doesn't require root. This is what I use:
Code:
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processInfoList = am.getRunningAppProcesses();
Click to expand...
Click to collapse
Following Note can be found in the android-doc:
"this method is only intended for debugging or building a user-facing process management UI."
And the "RunningAppProcessInfo"-class (given by the Method) doesnt provide any infos about the running time of a process.
So i think it's more reliable for me to read out the process-infos directly in the proc-filesystem.

Dalorikai said:
Following Note can be found in the android-doc:
"this method is only intended for debugging or building a user-facing process management UI."
And the "RunningAppProcessInfo"-class (given by the Method) doesnt provide any infos about the running time of a process.
So i think it's more reliable for me to read out the process-infos directly in the proc-filesystem.
Click to expand...
Click to collapse
1) True.
2) That's why I wrote this:
nikwen said:
The only way I see is running a background service and storing the launch time yourself.
Click to expand...
Click to collapse
3) But if the other method works and if you don't care about root rights as a requirement, it might be better. :good:

Dalorikai said:
what is the unit of the "se.sum_exec_runtime"-field? is it in nano-secs?
what does the point do in the value? does it indicates a floating-point value?
im kinda confused and didnt really find something meaningful about the unit (*-*)
and im not very handy with the kernel code from "lxr.linux.no"
Click to expand...
Click to collapse
replying to my own post i think the point in the value of the field indicates the milli-secs.
just an idea - im not sure but would be plausible if the unit is nano-secs.
what do u think or possibly know? ^^

Related

[Q] Debugging help needed

I have a user of my app who is having a problem running it. My code launches another activity in the same app, and he is saying it is stopping before it should & returning to the previous activity, and he doesn't see any Force Close warnings.
I have run my code in the emulator & on my phone, I can't reproduce the error. We both run Android 2.2 on our phones, his is an HTC EVO & mine is a HTC Wildfire, as far as I can tell his specs are better than mine so shouldn't cause an issue - I deliberately chose a low spec for for my dev work so the code ought to run on anything.
As a bit of an Andoid dev noob (but been coding for years), is there any easy way I can make a special build of the app to send to him that would log any errors that happen ? I'd like to get a stack dump as well if possible, as I'm not sure exactly what routine in the activity its crashing out in. The activity that crashes is Gallery with 9 images in it, he can't flick through them or select one. I'm stumped as to whats causing it, any assistance would be gratefully received.
Thanks.
Why not point to your app and let others here try it on their phones? It could simply be other apps installed on his phone interfering with your app.
Long time programmer here too and when I get to where you're at (and I"m sure you've put some hours into this LOL), I go back to STEP 1.
I comment-out any and all code but the bare minimum; break it down to the Intent, startActivity and maybe a Toast message in the second activity. Even parse down your XML files to bare minimum.
See if that works. Then, ADD BACK ONE LINE OF CODE AT A TIME Run program and make sure it works. Yeah, it's painful, but in my 20 years of coding, I've learned to put my pride aside and to not "pretend" all the code I've written is correct.
Sometimes on bigger projects, I"ll change or add a couple of lines of code, run a back up and test. Rinse and repeat LOL. That way, I know I"m only a couple of lines of code from what "used" to work.
Good Luck!
Thanks both of you.
old_dude - Its a paid app. Only £0.99 but I don't think people would pay to help me. There is a free version of the same app (with less functionality) that this guy can get to work. If your really interested the 2 versions are -
Plink Log - Free Version
Plink Log Pro - Paid version
Rootstonian - agreed thats the approach I'd normally take if I was having problems on my dev phone or the emulator. The problem is that its OK on my HTC Wildfire/Android2.2 but on this guys HTC EVO/Android2.2 its having problems. I dont really want to keep sending him .apks with 1 or 2 lines extra enabled just to see if that fixes his specific issue. I was hoping there was something I could code to catch whatever crashes the activity & log it somewhere for me to analyse. When I do PC dev work, I have a global exception handler that catches anything I dont explicitly handle, and dumps the full call stack into a Log File I can read later.
I think I'll just have to take the existing app & put loads of debug code into it to save messages into a log file & see what bits of code are being called & what isn't & then get him to email me the results.
Thanks for the ideas guys, its always useful to get input from another perspective.
Dave
Hmmmm, just discovered setDefaultUncaughtExceptionHandler - might be able to use that with printStackTrace. Sounds interesting.

Detect Package Launch

I am working on an application and I need to be able to have a service that can detect when applications are opened, and take action based on that.
I have looked everywhere, and have not found a way to do so. I have read documentation on broadcast receivers, intent handlers, I found nothing.
I did however, find an app that can do so. App Protector. It allows password protecting certain applications.
Can anybody please point me in the right direction?
Thanks!
this is actually a very good question. a BroadcastReciever only gets Intents directed at it, and wouldnt see Intents for other classes and Packages.
ill be very interested to know the answer
killersnowman said:
this is actually a very good question. a BroadcastReciever only gets Intents directed at it, and wouldnt see Intents for other classes and Packages.
ill be very interested to know the answer
Click to expand...
Click to collapse
Well I was looking for a BroadcastReceiver that was sent out by the system to indicate that an app was opened, but I did not come across anything.
this isnt possible.. to be able to monitor all intents would make android extremely insecure
http://groups.google.com/group/android-developers/browse_thread/thread/54ddc9d36a24d77b
but there are ways to know when an application is launched. you just have to be creative.
this will give you a list of all the applications running.
Code:
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
however to know when an app is launched you would need a timed loop and then check between versions of the List to see if there is a new app. this would suck the juice and be inneficient
AppProtector seem to access the eventlog. maybe you could have a ContentObserver attached to the event log
http://developer.android.com/reference/android/util/EventLog.html
http://developer.android.com/reference/android/database/ContentObserver.html
killersnowman said:
this isnt possible.. to be able to monitor all intents would make android extremely insecure
http://groups.google.com/group/android-developers/browse_thread/thread/54ddc9d36a24d77b
but there are ways to know when an application is launched. you just have to be creative.
this will give you a list of all the applications running.
Code:
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
however to know when an app is launched you would need a timed loop and then check between versions of the List to see if there is a new app. this would suck the juice and be inneficient
AppProtector seem to access the eventlog. maybe you could have a ContentObserver attached to the event log
http://developer.android.com/reference/android/util/EventLog.html
http://developer.android.com/reference/android/database/ContentObserver.html
Click to expand...
Click to collapse
Interesting.
I also found this:
Code:
String str = ((ActivityManager.RunningTaskInfo)this.am.getRunningTasks(1).get(0)).topActivity.getPackageName();
It's one of the things App Protector uses
It starts a new intent, pointing to their application, and passing the parameters of the package you tried to run
Take a look at Tasker it can defiantly do this.
rujelus22 said:
Take a look at Tasker it can defiantly do this.
Click to expand...
Click to collapse
He doesn't want it for scripting, but for use in his own program.
From something awesome

Linked List passing

I load a linked list of objects (i.e. a struct) at start of app. I want to pass the whole linked list to other Activity(s).
I can do linkListName.toArray() and pass via put.extra and re-create linked list in next Activity, but it just doesn't "feel" clean! ROFL
And most likely it's pass by value, not by reference (not sure if that makes a difference in my app yet, but I bet I'll need a pass by reference call). I've also read about Serialization and Parcels, but I think those are pass by value implementations too.
What I want to avoid is passing a linked list around my app; I would like to load it once, be able to have my custom class do whatever I need (adds, edits, deletes, moves etc.) on it.
Any ideas? I know I could probably just do everything in ONE Activity and just change my ContentViews as required, but I've read that can be troublesome. And note that I"m trying very hard to stay away from any database implementation just because I've done the database thing too many times.
TIA,
Roots
You could make the linked list protected instead of private and just pass a flag that tells your other activity to just access it via SomeActivity.myLinkedList
Protected makes the variable accessible by other classes in your package but not outside
From something awesome
And static...
From something awesome
Well ****, should have known that....THANKS! Guess my OOP is a bit rusty :-( ugh, I got it....seems to be ok...that is, I can see my methods when I do "ClassName.LinkedListName. "
Thank you so very much!!!!
Its happened to me before. Ive gotten caught up in Android Intents, Bundles, Extras, etc and was struggling to pass something till i stepped back and realized im still in Java... Its more of a mindset thing than anything else
From something awesome
08-06 15:46:27.354: INFO/System.out(408): This default is true
08-06 15:46:27.354: INFO/System.out(408): This default is false
Ha! My setter and getter methods are working across Activities! Woo Frikkn' Woo...I could send you $100 for that reply I'm so happy! Note to self: Must remember to write changes to file.
Just a note to ALL programmers, new and old: If you're trying to do something and it seems extremely difficult, you're probably doing it wrong. Go back to the basics and keep it simple stupid!

Way to store Preferences

Hey Guys,
I am creating a app to rename other apps via xposed and the main code is written. Now I simply want to make a interface where you can define a app to rename and then enter a new name. For the beginning I thought about a Activity where you enter the Package Name and the desired name. Later on I want to use a list view to show all apps, from where you can choose one to rename(Like App Settings etc.). To show the renamed apps I want to use a ListView. Now I am stuck with a problem: My xposed code works with an array to check and rename. The list view can be used with an array or an arraylist, but I need a way to store the preferences(which are stored in a array).
Do you have a good idea or a sample how to realise this? And does somebody know a nice App List type of thing(I googled, but the project there aren't usable with my kind of approach.)
GalaxyInABox said:
Hey Guys,
I am creating a app to rename other apps via xposed and the main code is written. Now I simply want to make a interface where you can define a app to rename and then enter a new name. For the beginning I thought about a Activity where you enter the Package Name and the desired name. Later on I want to use a list view to show all apps, from where you can choose one to rename(Like App Settings etc.). To show the renamed apps I want to use a ListView. Now I am stuck with a problem: My xposed code works with an array to check and rename. The list view can be used with an array or an arraylist, but I need a way to store the preferences(which are stored in a array).
Do you have a good idea or a sample how to realise this? And does somebody know a nice App List type of thing(I googled, but the project there aren't usable with my kind of approach.)
Click to expand...
Click to collapse
Ah the data storage problem... I think we all came across this at least once . I suppose you read this guide on the different options available? Well there are actually three options: SharedPreferences, text or csv file and SQL.
The first one would need some work around and is probably the slowest. You would save a separate string directly into the SharedPreferences (maybe in a new file to avoid collisions?) with the array name and its index somehow in the key. That's just two methods of coding but not the nicest way to do it.
The text or csv file however is the more common way, here you'd save your array in one line of the file, each item separated with a ; or some other char. Needs a bit more coding and also the WRITE_EXTERNAL_STORAGE permission on preKitKat if I remember correctly.
The third one is the nicest and most modular one. Because it makes use of SQL it needs quite a bit of knowledge and some coding (but less than the text file).
I guess for simple things that you want to do it is better to stay away from SQL for now unless you know how to use it and use the SharedPreferences.
Edit: take a look at the answers to this question, they give you the code as well... And you can use StringSets in ICS and above if the order of your list doesn't matter !
I'd say go down the SQLite DB way, chances are that if you plan on expanding your coding knowledge and want to keep creating apps you'll be needing to learn this in the future anyway so why delay?
Google AndroidHive and look at their SQL tutorial - I used it when learning and found it very informative
Sent from my HTCSensation using Tapatalk
Thank you very much! As coming from windows, first of all I thought about SQL as well, but it seems oversized for the set of data i want to store. I also took a look at the stackoverflow thread you linked. It looks easy to implement, but the need to use an external class file made me look for another way. I found this one, which works pretty well for me, as I look forward to interchange the method of saving the data with a better one using the SharedPreferences(which actually should be really easy with my code).
Maybe you can tell me yet another thing: Is there a way of declaring an object(like the ArrayList) to make it accessible from every class except from giving every class(activity) it's own "load the preferences" and "save the preferences" code block or sending intents all over the place? This would make saving much easier and allow me to update the preferences during runtime and without a reboot
Edit: This was my answer to.SimplicityApks ^^ I'll take a closer look at SQL now, since you, Jonny, told me that it' nevertheless necessary.
GalaxyInABox said:
Thank you very much! As coming from windows, first of all I thought about SQL as well, but it seems oversized for the set of data i want to store. I also took a look at the stackoverflow thread you linked. It looks easy to implement, but the need to use an external class file made me look for another way. I found this one, which works pretty well for me, as I look forward to interchange the method of saving the data with a better one using the SharedPreferences(which actually should be really easy with my code).
Maybe you can tell me yet another thing: Is there a way of declaring an object(like the ArrayList) to make it accessible from every class except from giving every class(activity) it's own "load the preferences" and "save the preferences" code block or sending intents all over the place? This would make saving much easier and allow me to update the preferences during runtime and without a reboot
Edit: This was my answer to.SimplicityApks ^^ I'll take a closer look at SQL now, since you, Jonny, told me that it' nevertheless necessary.
Click to expand...
Click to collapse
Welcome
You mean you want to make your ArrayList, which is an instance variable in the activity, accessible to every other class within your package without having an instance of your activity at hands? Well the basic solution would be to make the ArrayList static. But that is not recommended because it won't be created and garbage collected at the same time as your activity and also it's not a nice way .
If you had an instance of the activity it would be just using a public getter for it, but without I'd put your ArrayList into a separate class following the Singleton pattern. That way you have only one global instance which contains the ArrayList.
Thanks again for your reply! I changed my mind about the ArrayList and created a method, where everything is stored in the SharedPreferences and the ArrayList's only purpose is the use with the ListView and Adapter. This way I don't have to write the ArrayList to the SharedPreferences and changes will be much easier to control. Although I had to implement another type of save/load method to interact with the class thats being loaded by xposed. That was needed because of the restriction that you can only load SharedPreferences with a context, which my class doesn't have. It's an inconvenient way, but it works

[Q] How to run multiple processes at exactly the same time

I can not publish any code or any logs, because there is no real problem yet. I am a beginner in Android / Java and the OOP concept.
I need to run two processes at exactly the same time in my program. The processes are sound samples and requires played at exactly the same time to be synchronized with each other.
I call the methods on the lines one after the other, which gives me a delay when the first clip starts a few microseconds before. Depending on the hardware this delay will also vary enormously .. how do i run the commands, or call the methods exactly the same time?
I've been looking at adding a delay of the first method by a handler, but I do not want to do this but it does not guarantee accurate synchronization.
I am on track to use AsyncTask, and somehow run these processes simultaneously but in different threads ... I have no idea if I'm on the right track? Can anyone confirm that this is the right way, or provide information about what else I can do? Grateful for all the help I can get. I hope I have not used the wrong terms and that I have given you enough information so that you can understand my question. Thanks in advance.
Having two functions tied to the same event has worked for me in the past.
For example, if you have a play button and you set up two separate functions to run when that button is clicked, they should go at the exact same time. If your play button is pressed, it will fire both functions simultaneously.
Another more advanced approach would be to return the current time code of "sound a" and pause it until the time code of "sound b" reaches the current time of "sound a".
Im Saint said:
Having two functions tied to the same event has worked for me in the past.
For example, if you have a play button and you set up two separate functions to run when that button is clicked, they should go at the exact same time. If your play button is pressed, it will fire both functions simultaneously.
Another more advanced approach would be to return the current time code of "sound a" and pause it until the time code of "sound b" reaches the current time of "sound a".
Click to expand...
Click to collapse
Well "simultaneously" is a big word but you are right, even if one player lags behind the other one, we are talking about microseconds at most. And i doubt that anybody would even notice that.
And to OP:
In java there is a keyword called "synchronized" where one thread awaits the other. I have never used that and so i dont know how to use this. Maybe if you look it up on google it could prove useful to your project. But i actually dont think that you can technically accomplish this "true" synchronization you are thinking of... It is worth a try at least
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0
Have you considered buffering? you can buffer samples in some queue and start playing them after a decided delay / samples count, making sure you have samples from all the sources you need to synchronize
Thanks for the replies, any help is much appreciated!
Im Saint said:
Having two functions tied to the same event has worked for me in the past.
For example, if you have a play button and you set up two separate functions to run when that button is clicked, they should go at the exact same time. If your play button is pressed, it will fire both functions simultaneously.
Another more advanced approach would be to return the current time code of "sound a" and pause it until the time code of "sound b" reaches the current time of "sound a".
Click to expand...
Click to collapse
Good to hear, but can it be guaranteed that the function calls are performed exactly the same time? This is very necessary for various reasons.
Masrepus said:
Well "simultaneously" is a big word but you are right, even if one player lags behind the other one, we are talking about microseconds at most. And i doubt that anybody would even notice that.
And to OP:
In java there is a keyword called "synchronized" where one thread awaits the other. I have never used that and so i dont know how to use this. Maybe if you look it up on google it could prove useful to your project. But i actually dont think that you can technically accomplish this "true" synchronization you are thinking of... It is worth a try at least
Click to expand...
Click to collapse
This is what I also want to emphasize. With the greatness of the inner meaning of "simultaneousness", even if that someone would not notice anything, it's a necessity.
I will seriously undermine further the keyword synchronized. This sounds exactly like what I need. I will succeed and reconnect with the results!
pixeltech.dev said:
Have you considered buffering? you can buffer samples in some queue and start playing them after a decided delay / samples count, making sure you have samples from all the sources you need to synchronize
Click to expand...
Click to collapse
I have heard the word buffer before but never truly understood how it works syntactically, nor in Android / Java.
With what kind of content can this be done? All types of media, audio / picture / video? Do you have any keyword to search on or link to an example?
Invisible Algorithm said:
Thanks for the replies, any help is much appreciated!
I have heard the word buffer before but never truly understood how it works syntactically, nor in Android / Java.
With what kind of content can this be done? All types of media, audio / picture / video? Do you have any keyword to search on or link to an example?
Click to expand...
Click to collapse
Buffering is a technique where you first collect enough data (can be represented in any form but is usually done through collections) and once you have enough data you do something with it.
An example can be reading data in bytes form from one source (e.g. network channel), buffering it (storing it in some collection) and writing it to files when buffered data reaches some threshold size

Categories

Resources