broadcast to have application launch count - android

How can I get the launch count of all applications? I have the complete list of installed apps, and I have a broadcast when an application is installed, but I need the launch count of any apps.
I see this app with this. You have the cpu time, the foreground time, and the launch count... how do they do it??

Finally i do that! i create a AlarmManager that every minute check the running applications, if an application in running (background or active) i check the last time that i saw it. if this time is greater than one minute i increase the count.
Now i'm trying to have how many data the application sent to an external server, i have this data, but do you know if this data is from i have installed my application or from when i boot my smartphone?
Long txByte = TrafficStats.getUidTxBytes(listApp.getAppsRunning().get(i).getPid());
this code is for get the count time
for(int i=0; i< listApp.getAppsRunning().size(); i++)
{
String pName = listApp.getAppsRunning().get(i).getPackageName();
String Ldate = "0";
int Nrun = 0;
Long Ntime = null, Ndata = null ;
Cursor c=db.fetchInstalled(pName);
if(c.moveToFirst())
{
Nrun = c.getInt(2);
Ldate = c.getString(3);
Ntime = c.getLong(4);
Ndata = c.getLong(5);
Log.d("db", "last time: " + Nrun+ " time: " + Ldate);
}
if(Ldate.equalsIgnoreCase("0"))
{
Nrun++;
db.updateLaunchAndTime(Nrun, lastUpdated, pName, Ntime, Ndata);
}
else
{
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy h:mmaa");
Date lastDate = null;
Date currentDate = null;
try {
lastDate = dateFormat.parse(Ldate);
currentDate = dateFormat.parse(lastUpdated);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//int pid = android.os.Process.getUidForName(listApp.getAppsRunning().get(i).getPid());
Long txByte = TrafficStats.getUidTxBytes(listApp.getAppsRunning().get(i).getPid());
Log.d("pid process", "pid: " + listApp.getAppsRunning().get(i).getPid());
Ndata = txByte;
Log.d("data send", "send: " + Ndata);
long diff = currentDate.getTime() - lastDate.getTime();
if(diff > 100* 1000)
{
Log.d("db", "difference plus 1 min app: " + pName);
Nrun++;
}
Ntime = Ntime+diff;
db.updateLaunchAndTime(Nrun, lastUpdated, pName, Ntime, Ndata);
}
//db.insertRunningP(pName , lastUpdated);
}
db.close()
I checked the power consume of this code and is less than 3% of total battery, so for now this is the best solution that i have found

I've never done it before, but I'm pretty sure http://developer.android.com/reference/android/app/ActivityManager.html provides the information you need.

if you had rooted your device, you also can read the usage stats files in /data/system/usagestats/usage-* for detail infomation.

Related

GreenDAO clears cache randomly

I´ve got two buttons in an Android activity with these two methods attached. One of them loads data and another just retrive it. Of course, the first time I execute the second method it gets data from cache and consumed time is very low, but further calls to this method always becomes in bigger times (as bigs as the consumed by the load data method), in other words, it seems that cache clears "randomly".
daoSession is an static attribute and I just call several times the getDataFromCacheById method (press the same button repeteadly, nothing else). Why does it clears cache? Is there any way to keep the cache data in memory always?
Best regards
public void onMyLoadButtonClick(View view) {
listaIds.clear();
List<String> lTexto = new ArrayList<String>();
Date iniTime = new Date();
LibroDao libroDao = daoSession.getLibroDao();
for (Libro tempLibro : libroDao.loadAll()) {
for (Nota tempNota : tempLibro.getNotaList()) {
lTexto.add(tempNota.getText());
listaIds.add(tempNota.getId());
}
}
Date finTime = new Date();
long tiempoTotal = finTime.getTime() - iniTime.getTime();
Log.v(LOG_TAG, "Overall time = " + tiempoTotal + " lTextoSize = " + lTexto.size());
}
public void getDataFromCacheById(View view) {
List<String> lTexto2 = new ArrayList<String>();
Date iniTime2 = new Date();
for (Long tempId : listaIds) {
lTexto2.add(noteDao.load(tempId).getText());
}
Date finTime2 = new Date();
long tiempoTotal2 = finTime2.getTime() - iniTime2.getTime();
Log.v(LOG_TAG, "Tiempo total de la operación Prueba Caché = " + tiempoTotal2 + " lTextoSize = " + lTexto2.size());
}

Get alarm infomation

I am implementing an application in which I have to display alarm info (day, time..) if it is available. Is there anybody know how to access to alarm info?
Thanks so much
Result: Finally, I can retrieve alarm information by using Curious's answer as above. Moreover, when I explored Deskclock app in /packages/apps/ I found one more way to get next alarm format (I used this way to display alarm info on my LockScreen because it is more simple than Curious's one :) )
String nextAlarm = Settings.System.getString(getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
if(TextUtils.isEmpty(nextAlarm) {
Log.v(TAG, "nextAlarm is empty");
} else {
Log.v(TAG, "nextAlarm is :" + nextAlarm);
}
The next alarm format like this:
Sat 09:00
The disadvantage point is that it can only run in system environment (you have to embed them to Android source -> build it and run by image file).
Try something like this
final String tag_alarm = "tag_alarm";
Uri uri = Uri.parse("content://com.android.alarmclock/alarm")
Cursor c = getContentResolver().query(uri, null, null, null, null);
Log.i(tag_alarm, "no of records are" + c.getCount());
Log.i(tag_alarm, "no of columns are" + c.getColumnCount());
if (c != null) {
String names[] = c.getColumnNames();
for (String temp : names) {
System.out.println(temp);
}
if (c.moveToFirst()) {
do {
for (int j = 0; j < c.getColumnCount(); j++) {
Log.i(tag_alarm, c.getColumnName(j);
+ " which has value " + c.getString(j));
}
} while (c.moveToNext());
}
}

how to use SerialExecutor with AsyncTask (API < 11)

I've an app that is used by carers to sign in to the system using their android phones. They scan a QRcode or swipe an NFC tag to get the client's information, scan time and location. The latter info constitutes a transaction. The transaction is placed in the phone's DB as well as submitted to a server via HTTP.
All works well as all transactions are put in DB and posted to web service until i have to make two transactions at the same time. A transaction is made by calling AsyncTask as it's a network call and so not to block UI thread. Both transactions are made to the web service but not all the data is sent to DB. I've commented out some code and made one Async post at a time and the data is then sent fine.
The problem
When one AsyncTask is running the other starts. When this happens the first AsyncTask doesn't work correctly. I have found the following thread where there is a similar problem and using a SerialExecutor seems to be the answer.
serialexecutor
https://stackoverflow.com/questions/6645203/android-asynctask-avoid-multiple-instances-running
Could anyone help me implement the 2 following AsyncTasks in a SerialExecutor, I'm fairly new to Android and i'm struggling to start this off. I'd like apd to execute and finish then apd3 to execute after. All in a serial fashion.
Thanks in advance Matt
String temp_tagType = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TYPE));
String temp_tagCompId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_COMPANY_ID));
String temp_PersonId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_PERSON_ID));
String temp_tagName = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_NAME));
String temp_tagId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TAG_ID));
String temp_tagScanTime = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));
String temp_tagLatitude = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TRANSACTIONS_LATITUDE));
String temp_tagLongitude = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TRANSACTIONS_LONGITUDE));
if(temp_tagId == null){
temp_tagId = "notag";
}
String manualM = "M";
Log.e(TAG, " temp name and status = " + temp_tagName + " " + manualM);
////////insert the temp variables with the status set to M
ContentValues values = new ContentValues();
values.putNull(LoginValidate.C_ID);
values.put(LoginValidate.C_TYPE, temp_tagType);
values.put(LoginValidate.C_COMPANY_ID, nfcscannerapplication.getCompId());
values.put(LoginValidate.C_PERSON_ID, temp_PersonId);
values.put(LoginValidate.C_NAME, temp_tagName);
values.put(LoginValidate.C_TAG_ID, temp_tagId);
values.put(LoginValidate.C_STATUS, manualM);
values.put(LoginValidate.C_TAG_SCAN_TIME, manualLogoutTime);
values.put(LoginValidate.C_TRANSACTIONS_LATITUDE, temp_tagLatitude);
values.put(LoginValidate.C_TRANSACTIONS_LONGITUDE, temp_tagLongitude);
DateTime now = new DateTime();
DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime = df.print(now);
Log.e(TAG, "formattedNowTime = " + formattedNowTime);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String manualTime = df2.print(timeSetOnSpinner);
Log.e(TAG, "about to put " + temp_tagName + " into DB");
nfcscannerapplication.loginValidate.insertIntoTransactions(values);
String[] params = new String[]{nfcscannerapplication.getCompId(), temp_tagId, temp_PersonId, nfcscannerapplication.getCarerID(),
manualTime, formattedNowTime, manualM, getDeviceName(), temp_tagLatitude, temp_tagLongitude};
AsyncPostData apd = new AsyncPostData();
apd.execute(params);
///////////////now carry on as usual with the last actual tag that has been scanned
Log.e(TAG, "about to insert the current record after inserting the manual logout");
if(tagId == null){
tagId = _tagId;
}
ContentValues values3 = new ContentValues();
values3.putNull(LoginValidate.C_ID);
values3.put(LoginValidate.C_TYPE, tagType);
values3.put(LoginValidate.C_COMPANY_ID, nfcscannerapplication.getCompId());
values3.put(LoginValidate.C_PERSON_ID, tagPerson);
values3.put(LoginValidate.C_NAME, tagUserName);
values3.put(LoginValidate.C_TAG_ID, tagId);
values3.put(LoginValidate.C_STATUS, IN);
values3.put(LoginValidate.C_TAG_SCAN_TIME, tagScanTime.getMillis());
values3.put(LoginValidate.C_TRANSACTIONS_LATITUDE, tagLatitude);
values3.put(LoginValidate.C_TRANSACTIONS_LONGITUDE, tagLongitude);
// make the current transaction out
DateTime now3 = new DateTime();
DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime3 = df3.print(now3);
Log.e(TAG, "formattedNowTime = " + formattedNowTime3);
String formattedTagScanTime3 = df3.print(tagScanTime);
Log.e(TAG, "about to put " + tagUserName + " into DB");
nfcscannerapplication.loginValidate.insertIntoTransactions(values3);
String[] params3 = new String[]{nfcscannerapplication.getCompId(), tagId, tagPerson, nfcscannerapplication.getCarerID(),
formattedTagScanTime3, formattedNowTime, IN, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd3 = new AsyncPostData();
apd3.execute(params3);
.

too much time in reading sms from database and storing it in to text file

I'm reading sms record from database and write them into text file. But it takes too much time 3 to 4 mins to read n write 3500 records. If records are much more than that it takes plenty of time which is not appreciable. My code is:
final Cursor cur1 = c.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, "date ASC");
final int size = cur1.getCount();
final int sleeptimer = size;
final SMS [] sms = new SMS[size];
final String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "account.txt";
FileWriter fw = null;
try {
fw = new FileWriter(baseDir);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final BufferedWriter writer = new BufferedWriter(fw);
Thread myThread = new Thread()
{
public void run()
{
try
{
int currentwait = 0;
int j=0;
while(currentwait < sleeptimer)
{
sleep(200);
currentwait+=200;
for(int i = 0 ; i < 200 ; i++)
{
if(!cur1.moveToNext())
{
break;
}
ContactInfo p = new ContactInfo();
String content = cur1.getString(cur1.getColumnIndex("body"));
String number = cur1.getString(cur1.getColumnIndex("address"));
long date = cur1.getLong(cur1.getColumnIndex("date"));
String protocol = cur1.getString(cur1.getColumnIndex("protocol"));
String name = p.getName(number, c);
String type = null;
Calendar cal=Calendar.getInstance();
cal.clear();
cal.setTimeInMillis(date);
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal);
if( protocol == null )
{
type = "Outbox";
}
else
type = "Inbox";
try{
writer.write("Type: " + type);
writer.newLine();
writer.write("Name: " + number+"<"+name+">");
writer.newLine();
writer.write("Date: " + date_time);
writer.newLine();
writer.write("Content: " + content);
writer.newLine();
writer.newLine();
} catch (IOException e) {
Log.i("INFO", e.getMessage().toString());
}
//Log.i("INFO", content+" "+j);
sms[j] = new SMS(type , name , number , date_time , content );
j++;
}
}
}
catch(Exception e)
{
}
finally{
try{
writer.flush();
writer.close();
}
catch (Exception e) {
}
uploadtoserver(baseDir);
}
}
};
myThread.start();
any idea to improve it ???thanks :)))
Just remove this line:
sleep(200);
Call setMaxSqlCacheSize to increase the cache size. Default is 10. Try setting 20 first and see whether the time reduces to half..
Or/And
You can execute this sqlite query before performing any operation on db and see if that improves the speed. Changing the temp store to memory should improve the read write speed..
PRAGMA temp_store = 2; /* 0 | DEFAULT | 1 | FILE | 2 | MEMORY; */
When temp_store is MEMORY (2) temporary tables and indices are kept in as if they were pure in-memory databases memory
Also
PRAGMA page_size = bytes;
Query or set the page size of the database. The page size must be a power of two between 512 and 65536 inclusive.
Probably you can pass these statements either to execSQL(String sql) or to query(). Try and let me know how it works.
Check out other PRAGMAs that Sqlite supports: http://www.sqlite.org/
Update:
From documentation of query API:
For best performance, the caller should follow these guidelines:
Provide an explicit projection, to prevent reading data from storage that aren't going to be used.
Use question mark parameter markers such as 'phone=?' instead of explicit values in the selection parameter, so that queries that differ only by those values will be recognized as the same for caching purposes.

How to get CPU usage statistics on Android?

I want to get the overall CPU usage on Android, similar to what Windows' Task Manager does. I can parse the output of the top program included in Android, but if there is a API call that does the same thing, it would be better.
Any pointers?
ATTENTION: This answer is old and does NOT work on newer versions of Android due to enhanced security mechanisms.
For complete CPU usage (not for each process) you can use:
/**
*
* #return integer Array with 4 elements: user, system, idle and other cpu
* usage in percentage.
*/
private int[] getCpuUsageStatistic() {
String tempString = executeTop();
tempString = tempString.replaceAll(",", "");
tempString = tempString.replaceAll("User", "");
tempString = tempString.replaceAll("System", "");
tempString = tempString.replaceAll("IOW", "");
tempString = tempString.replaceAll("IRQ", "");
tempString = tempString.replaceAll("%", "");
for (int i = 0; i < 10; i++) {
tempString = tempString.replaceAll(" ", " ");
}
tempString = tempString.trim();
String[] myString = tempString.split(" ");
int[] cpuUsageAsInt = new int[myString.length];
for (int i = 0; i < myString.length; i++) {
myString[i] = myString[i].trim();
cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
}
return cpuUsageAsInt;
}
private String executeTop() {
java.lang.Process p = null;
BufferedReader in = null;
String returnString = null;
try {
p = Runtime.getRuntime().exec("top -n 1");
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (returnString == null || returnString.contentEquals("")) {
returnString = in.readLine();
}
} catch (IOException e) {
Log.e("executeTop", "error in getting first line of top");
e.printStackTrace();
} finally {
try {
in.close();
p.destroy();
} catch (IOException e) {
Log.e("executeTop",
"error in closing and destroying top process");
e.printStackTrace();
}
}
return returnString;
}
Have fun with it :)
You can read /proc/stat and parse the file contents. The first line is like:
cpu 79242 0 74306 842486413 756859 6140 67701 0
The meanings of the columns are as follows, from left to right:
- 1st column : user = normal processes executing in user mode
- 2nd column : nice = niced processes executing in user mode
- 3rd column : system = processes executing in kernel mode
- 4th column : idle = twiddling thumbs
- 5th column : iowait = waiting for I/O to complete
- 6th column : irq = servicing interrupts
- 7th column : softirq = servicing softirqs
Average idle percentage :
X % = ( idle * 100 ) / ( user + nice + system + idle + iowait + irq + softirq )
You can compute the difference in idle between time deltas, and figure CPU usage.
You can reference the "DevTools" project.
Using ActivityManager you can get lots information, such as ActivityManager.RunningAppProcessInfo, ActivityManager.RunningTaskInfo, ...
But I am not sure the result will same as 'top' command.
see
ActivityManager

Categories

Resources