how to Get epoch timestamp by using event.timestamp only in android - android

I am having a trouble getting a timestamp string from onSensorChanged method, than write it into a Log File as this example Magnitic Timestamp column, i`m studding java by creating a sensor app.
In this app i used Calendar and Date method to get other sensors timestamp but in this case i want to use only timestamp.
Result is: 1970/01/01_08:59:59:926 but i want to get nows date and time like this : 2013/11/01_14:17:02:673
I am using the following code to write the Log File:
final SensorEventListener magniListener = new SensorEventListener() {
private float magnidT;
private long magniLogFileTimestamp;
#Override
public void onSensorChanged(SensorEvent event) {
magniLogFileTimestamp = (event.timestamp - System.nanoTime()) / 1000000L;
if (magnitimestamp != 0) {
magnidT = (event.timestamp - magnitimestamp);
magniValueX = event.values[0];
magniValueY = event.values[1];
magniValueZ = event.values[2];
//here write the sensor values and timestamp to CSV file
if (magniFile != null) {
magniFile.print(String.valueOf(sensorTimestamp
.format(magniLogFileTimestamp)));
//sensorTimestamp = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss:SSS");
magniFile.print("," + String.valueOf(magniValueX) + ","
+ String.valueOf(magniValueY) + ","
+ String.valueOf(magniValueZ));
magniFile.println();
}
}
magnitimestamp = event.timestamp;
magniX.setText("X-axis: " + String.valueOf(magniValueX));
magniY.setText("Y-axis: " + String.valueOf(magniValueY));
magniZ.setText("Z-axis: " + String.valueOf(magniValueZ));
magnDelayValue.setText("Magnitic Delay: "
+ String.valueOf(magnidT * NS2MS) + " ms");
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
magnitimestamp = 0;
magniLogFileTimestamp = 0;
}
};
I can't get it right. Any suggestions? Thank you.

If you want to get epoch in milliseconds use:
System.currentTimeMillis();
If you want to get printable date, try:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String datevalue = dateFormat.format(date);
Hope this helps.

I think the problem lies in magniLogFileTimestamp = (event.timestamp - System.nanoTime()) / 1000000L;. If you subtract the time-stamp with current time, then you get the offset time which is considerably small, hence the date value near the epoch (1970/01/01).
Instead of subtracting it, just use the event.timestamp directly.
magniFile.print(sensorTimestamp.format(event.timestamp / 1000000));

Related

Decimal format for another Decimal format on Android

I'm having trouble formatting this decimal value format (8487.0) for that format. "8.48".
I have tried the solution of other issues posted here but I did not succeed.
Example:
Double n1 = Double.parseDouble (String.valueOf (8487.0));
DecimalFormat dec = new DecimalFormat ("#. ##");
String credits = dec.format (n1);   Log.d (TAG, "test" + credits);
Currently it has the output like this: 8487
Any help is welcomed, Thanks.
You can use String format
String answer = String.format("%.2f", (8487.0 / 1000));
Log.d(TAG, answer); //8.49
There are two cases; whether you want to round off or not. Here's the sample code for both the cases.
double d = 8487.0;
d /= 1000;
DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.FLOOR);
String notRounded = f.format(d);
System.out.println("Not Rounded: " + notRounded);
f.setRoundingMode(RoundingMode.HALF_UP);
String rounded = f.format(d);
System.out.println("Rounded: " + rounded);
So, do you want to reduce the number by a factor 1000 ? e.g. g to kg ?
Double n1 = Double.parseDouble (String.valueOf (8487.0));
Double n2 = n1 / 1000;
DecimalFormat dec = new DecimalFormat ("#. ##");
String credits = dec.format(n2);
Log.d (TAG, "test" + credits);

Android get the selected audio file's duration from storage [duplicate]

How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list
And another:
sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
String out = "";
// get mp3 info
// convert duration to minute:seconds
String duration =
metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("time", duration);
long dur = Long.parseLong(duration);
String seconds = String.valueOf((dur % 60000) / 1000);
Log.v("seconds", seconds);
String minutes = String.valueOf(dur / 60000);
out = minutes + ":" + seconds;
if (seconds.length() == 1) {
txtTime.setText("0" + minutes + ":0" + seconds);
}else {
txtTime.setText("0" + minutes + ":" + seconds);
}
Log.v("minutes", minutes);
// close object
metaRetriever.release();
You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.
Here is the Kotlin version:
var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
metaRetriever.setDataSource(filePath)
var out:String = ""
var txtTime:String = ""
var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("DURATION VALUE", duration)
var dur:Long = duration.toLong()
var seconds:String = ((dur % 60000)/1000).toString()
Log.d("SECONDS VALUE", seconds)
var minutes:String = (dur / 60000).toString()
out = minutes + ":" + seconds
if (seconds.length == 1){
txtTime = "0" + minutes + ":0" + seconds
}
else {
txtTime = "0" + minutes + ":" + seconds
}
Log.d("MINUTES VALUE", minutes)
Log.d("FORMATTED TIME", txtTime)
metaRetriever.release()
If you want to support older Android versions, you can use a 3rd party library. For example http://www.jthink.net/jaudiotagger/ works fine, though it's relatively space consuming for an Android application (a little less than 1 MB).
True programmers would of course parse the duration from the binary file without using any libraries ;) I didn't have enough skill for this.
I found this more accurate getLength with FFmpeg
int soundLength = (int) new SoxController(context, new File(""), shell).getLength(soundPath);

FaceRecognition with javacv android

I'm following javacv Face Detection/Recognition code, there is confusion regarding face recognition.. What I'm doing is (Sorry if it sounds stupid but I'm stuck)
1) Detect Face crop it and save it to sdcard and place path in learn.txt file (Learning part)
2) Detect Face crop it and find it in existing faces whether it exists or not, but it always return nearest position even if the face doesn't exist in sample faces..
what I'm doing wrong?
// Method, I'm using to recognize face
public Integer recognizeFace(Bitmap face, Context context) {
Log.i(TAG, "===========================================");
Log.i(TAG, "recognizeFace (single face)");
float[] projectedTestFace;
float confidence = 0.0f;
int nearest = -1; // closest match -- -1 for nothing.
int iNearest;
if (trainPersonNumMat == null) {
return null;
}
Log.i(TAG, "NUMBER OF EIGENS: " + nEigens);
// project the test images onto the PCA subspace
projectedTestFace = new float[nEigens];
// Start timing recognition
long startTime = System.nanoTime();
testFaceImg = bmpToIpl(face);
// saveBmp(face, "blah");
// convert Bitmap it IplImage
//testFaceImg = IplImage.create(face.getWidth(), face.getHeight(),
// IPL_DEPTH_8U, 4);
//face.copyPixelsToBuffer(testFaceImg.getByteBuffer());
// project the test image onto the PCA subspace
cvEigenDecomposite(testFaceImg, // obj
nEigens, // nEigObjs
new PointerPointer(eigenVectArr), // eigInput (Pointer)
0, // ioFlags
null, // userData
pAvgTrainImg, // avg
projectedTestFace); // coeffs
// LOGGER.info("projectedTestFace\n" +
// floatArrayToString(projectedTestFace));
Log.i(TAG, "projectedTestFace\n" + floatArrayToString(projectedTestFace));
final FloatPointer pConfidence = new FloatPointer(confidence);
iNearest = findNearestNeighbor(projectedTestFace, new FloatPointer(pConfidence));
confidence = pConfidence.get();
// truth = personNumTruthMat.data_i().get(i);
nearest = trainPersonNumMat.data_i().get(iNearest); // result
// get endtime and calculate time recognition process takes
long endTime = System.nanoTime();
long duration = endTime - startTime;
double seconds = (double) duration / 1000000000.0;
Log.i(TAG, "recognition took: " + String.valueOf(seconds));
Log.i(TAG, "nearest = " + nearest + ". Confidence = " + confidence);
Toast.makeText(context, "Nearest: "+nearest+" Confidence: "+confidence, Toast.LENGTH_LONG).show();
//Save the IplImage so we can see what it looks like
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "/sdcard/saved_images/" + nearest + " " + String.valueOf(seconds) + " " + String.valueOf(confidence) + " " + n + ".jpg";
Log.i(TAG, "Saving image as: " + fname);
cvSaveImage(fname, testFaceImg);
return nearest;
} // end of recognizeFace
EDIT The confidence is always negative!
Thanks in advance

broadcast to have application launch count

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.

Get mp3 duration in android

How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list
And another:
sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
String out = "";
// get mp3 info
// convert duration to minute:seconds
String duration =
metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("time", duration);
long dur = Long.parseLong(duration);
String seconds = String.valueOf((dur % 60000) / 1000);
Log.v("seconds", seconds);
String minutes = String.valueOf(dur / 60000);
out = minutes + ":" + seconds;
if (seconds.length() == 1) {
txtTime.setText("0" + minutes + ":0" + seconds);
}else {
txtTime.setText("0" + minutes + ":" + seconds);
}
Log.v("minutes", minutes);
// close object
metaRetriever.release();
You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.
Here is the Kotlin version:
var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
metaRetriever.setDataSource(filePath)
var out:String = ""
var txtTime:String = ""
var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("DURATION VALUE", duration)
var dur:Long = duration.toLong()
var seconds:String = ((dur % 60000)/1000).toString()
Log.d("SECONDS VALUE", seconds)
var minutes:String = (dur / 60000).toString()
out = minutes + ":" + seconds
if (seconds.length == 1){
txtTime = "0" + minutes + ":0" + seconds
}
else {
txtTime = "0" + minutes + ":" + seconds
}
Log.d("MINUTES VALUE", minutes)
Log.d("FORMATTED TIME", txtTime)
metaRetriever.release()
If you want to support older Android versions, you can use a 3rd party library. For example http://www.jthink.net/jaudiotagger/ works fine, though it's relatively space consuming for an Android application (a little less than 1 MB).
True programmers would of course parse the duration from the binary file without using any libraries ;) I didn't have enough skill for this.
I found this more accurate getLength with FFmpeg
int soundLength = (int) new SoxController(context, new File(""), shell).getLength(soundPath);

Categories

Resources