Android : get timing information of running application - android

I use this code to get information of currently running applications in android app.
I want to how I can get timing information(start time) of currently running applications

long millisSinceBoot = SystemClock.elapsedRealtime();
System.out.println("00000 "+millisSinceBoot);
System.out.println("11111 "+values.get(position).activeSince+" "+values.get(position).process);
long time = ((millisSinceBoot - values.get(position).activeSince)/1000);
int[] vals = splitToComponentTimes(time);
String time1 = vals[0]+":"+vals[1]+":"+vals[2];
time_list.add(time);
timer.setText(time1);
System.out.println("valssssss "+vals[0]+" "+vals[1]);

Related

is timezoneinfo.converttime works with some devices only at xamarin froms?

I'm using Xamarin forms in my android app I'm getting the datetime that I converted to
Egypt time but some devices read it nulls or countries I don't know the reason really but some others read it?
and that is my code
DateTime date = DateTime.Now;
var test = TimeZoneInfo.ConvertTime(date, TimeZoneInfo.FindSystemTimeZoneById("Africa/Cairo"));
It might help you
DateTime now = DateTime.UtcNow;
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Africa/Cairo Standard Time");
TimeSpan utcOffset = timeZoneInfo.GetUtcOffset(now);
DateTime cairoTime = new DateTime(now.Ticks + utcOffset.Ticks, DateTimeKind.Local);

Custom UUID for multiple Bluetooth connection in Android

I have an android device acting as server which connects to multiple bluetooth android clients.
I understand the concept of UUID and how it is unique.
My question is, can I use the same UUID for all my clients connecting to my server?
If not, how do I generate a UUID for my clients programmatically and let my server know about their UUIDs.
The problem started appearing after Android 8.1 where you no longer had access to bluetooth MAC address which I initially used to generate UUIDs for client android devices.
You can generate one like this.
First, is needed to generate as long the 64 least and most significant bits:
private static long get64LeastSignificantBitsForVersion1() {
Random random = new Random();
long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
long variant3BitFlag = 0x8000000000000000L;
return random63BitLong + variant3BitFlag;
}
private static long get64MostSignificantBitsForVersion1() {
LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
Duration duration = Duration.between(start, LocalDateTime.now());
long seconds = duration.getSeconds();
long nanos = duration.getNano();
long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
long version = 1 << 12;
return
(timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime;
}
next you can use the above methods to build one UUID:
public static UUID generateType1UUID() {
long most64SigBits = get64MostSignificantBitsForVersion1();
long least64SigBits = get64LeastSignificantBitsForVersion1();
return new UUID(most64SigBits, least64SigBits);
}
Answer:
I finally found out that you can use a custom UUID using a generator and it works with multiple devices.
The UUID must be unique and should not collide with the ones that are common & public.
Hopefully someone finds it useful

Using UsageStatsManager to get the foreground app

I'm trying to use UsageStatsManager to get the foreground app on a Nexus 5 with Marshmallow. I remember it used to work, but for some reason I'm getting null strings for package/class names now.
Here's my implementation
public String[] getForegroundPackageNameClassNameByUsageStats() {
String packageNameByUsageStats = null;
String classByUsageStats = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
final long INTERVAL = 1000;
final long end = System.currentTimeMillis();
final long begin = end - INTERVAL;
final UsageEvents usageEvents = mUsageStatsManager.queryEvents(begin, end);
while (usageEvents.hasNextEvent()) {
UsageEvents.Event event = new UsageEvents.Event();
usageEvents.getNextEvent(event);
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
packageNameByUsageStats = event.getPackageName();
classByUsageStats = event.getClassName();
Log.d(TAG, "packageNameByUsageStats is" + packageNameByUsageStats + ", classByUsageStats is " + classByUsageStats);
}
}
}
return new String[]{packageNameByUsageStats,classByUsageStats};
}
For some reason, it doesn't go into the while loop, i.e. usageEvents.hasNextEvent() is false. Because of this, it returns null package/class names.
Any idea what I'm doing wrong?
Thanks.
OK, so I found that once I set the interval to 10000 instead of 1000, it works. Apparently a 1s interval is too small.
I am using this myself. I think the usage stats will only be updated when an app comes to foreground. So if the foreground app got to the foreground (and stayed) before your 'begin' timestamp then you will not get it. :(
On the other hand when you use a long time ago you will get a giant list where you only need the highest time to determine the foreground app.
So what I do is I create 3 different times: 1min ago, 1 hour ago and 12 hours ago.
When I get an empty list on 1min I repeat request with 1h and so on. That way I get foreground most of the time. But I never get it to work ALL of the time.
I really miss the old way of just asking the package manager which app is foreground (prior to android 5), the new way is a bit messy.

Is there a preferred way to get the system time in cocos2d-x?

I am writing a cross-platform application in Cocos2d-x. I need to get the time to create a countdown clock to a certain time of day. Since it is in C++, I can use time(...), mktime(...), and difftime(...) if I need to as a direct approach.
Is there a preferred method in Cocos2d-x for doing this in a cross-platform way (i.e. something built directly into the framework)? I want the app to work the same on iPhones, iPads, and Android.
try this:
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
CCLog("year------->%04d",timeinfo->tm_year+1900);
CCLog("month------->%02d",timeinfo->tm_mon+1);
CCLog("day------->%02d",timeinfo->tm_mday);
CCLog("hour------->%02d",timeinfo->tm_hour);
CCLog("minutes------->%02d",timeinfo->tm_min);
CCLog("seconds------->%02d",timeinfo->tm_sec);
Try this code
static inline long millisecondNow()
{
struct cc_timeval now;
CCTime::gettimeofdayCocos2d(&now, NULL);
return (now.tv_sec * 1000 + now.tv_usec / 1000);
}
I used this function to get current time in millisecond. I am new in cocos2d-x so hope this can be helpful.
You should try this lib, I just tested and it works fine.
https://github.com/Ghost233/CCDate
If you receive some wrong values, set timezoneOffset = 0;
Note: 0 <= month <= 11
You can sheduleUpdate in clock class.
The update call with a float argument which is a delta time in seconds after last calls, this method is called every frame and cocos2d-x get time through from the system and count the delta.
I thought this code would do the trick:
static inline long millisecondNow()
{
struct cc_timeval now;
CCTime::gettimeofdayCocos2d(&now, NULL);
return (now.tv_sec * 1000 + now.tv_usec / 1000);
}
HOWEVER, only gives a part of what I need. In general, I need a real "date and time" object (or structure), not just the time of day in milliseconds.
The best solution, for now, seems to be using the "classic" localtime, mktime, difftime trifecta in C++. I have a few examples below of some basic operations...I may cook up a general class to do these kinds of operations, but for now, these are a good start and show how to get moving:
double Utilities::SecondsTill(int hour, int minute)
{
time_t now;
struct tm target;
double seconds;
time(&now);
target = *localtime(&now);
target.tm_hour = hour;
target.tm_min = minute;
target.tm_sec = 0;
seconds = difftime(mktime(&target),now);
return seconds;
}
DAYS_OF_WEEK_T Utilities::GetDayOfWeek()
{
struct tm tinfo;
time_t rawtime;
time (&rawtime);
tinfo = *localtime(&rawtime);
return (DAYS_OF_WEEK_T)tinfo.tm_wday;
}

Plot graph using multiple database values in Android app

I am currently using afreechart to plot a graph in my Android app. I am using the TimeSeries graph, that they've exemplified in their sample app. For me, data to be extracted from two databases.Two questions :
1. How to plot this TimeSeries graph using values from my two databases?
2. The whole graph is not as smooth as one would want to. Especially when scrolling or flicking. And hence, it's inconsistent with the app design. Any way I could make it smoother?
If the questions above seems unnecessary or in some way wrong, please point me to a way where I can plot a graph using multiple database values, even if it's not using afreechart. Thanks.
I tried using simple 'for' loops in createDataset(), like :
private static XYDataset createDataset() {
mfirstDbHelper.open();
msecondDbHelper.open();
int firstdb_count = (int) DatabaseUtils.queryNumEntries(mfirstDbHelper.mDb,firstDbAdapter.DATABASE_TABLE);
int seconddb_count = (int) DatabaseUtils.queryNumEntries(msecondDbHelper.mDb,secondDbAdapter.DATABASE_TABLE);
TimeSeriesCollection dataset = new TimeSeriesCollection();
for(int i=1;i<=seconddb_count;i++){
Cursor seconddb = msecondDbHelper.fetchItem(i);
TimeSeries s1 = new TimeSeries(seconddb.getString(
seconddb.getColumnIndexOrThrow(secondDbAdapter.KEY_ITEMNAME)));
for(int j=1;j<=firstdb_count;j++){
Cursor firstdb = mfirstDbHelper.fetchItem(j);
int first_sp_id = Integer.parseInt(firstdb.getString(
firstdb.getColumnIndexOrThrow(firstDbAdapter.KEY_ID)));
if(first_sp_id == i){
int value = Integer.parseInt(firstdb.getString(
firstdb.getColumnIndexOrThrow(firstDbAdapter.KEY_VALUE)));
String date = firstdb.getString(
firstdb.getColumnIndexOrThrow(firstDbAdapter.KEY_DATE));
String dateParts[] = date.split("-");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
int d = Integer.parseInt(day);
int m = Integer.parseInt(month);
int y = Integer.parseInt(year);
s1.add(new Day(d,m,y), value);
dataset.addSeries(s1);
}
firstdb.close();
}
seconddb.close();
}
mfirstDbHelper.close();
msecondDbHelper.close();
return dataset;
}
}
I have changed the Month() in sample to Day(), and have made sure there's no error in that area.
Am getting the error:
ERROR/AndroidRuntime(706): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kev/com.kev.MyProject}: java.lang.NullPointerException
Also, obviously, this code redraws the graph "s1" over and over again. I do not know how to overcome this problem, and the error. Am still fairly new to programming, especially Android app development, so any blunders above, feel free to smack me in the head and correct my code.
Oh, one more thing, I can't use startManagingCursor() since it's a DemoView and not Activity. So, don't know if its causing any problems either.
Afreechart TimeSeries sample:
http://code.google.com/p/afreechart/source/browse/#svn%2Ftrunk%2Fafreechart_sample%2Fsrc%2Forg%2Fafree%2Fchart%2Fdemo
Afreechart TimeSeries sample - View:
http://code.google.com/p/afreechart/source/browse/trunk/afreechart_sample/src/org/afree/chart/demo/view/TimeSeriesChartDemo01View.java
Thanks again, for your time. :)

Categories

Resources