4

I want to store time as "dateString" when gyroscope reading x=0.0,y=0.0,z=0.0 & when x>0.0 && y>0.0 && z>0.0 store time as "dateString1". I am not able to time if condition is met because it is taking current time of my phone. It is continuously running so not able to get time when event is happening what is the solution for same ?

enter image description here

Example- if my phone is on rest ,gyroscope sensor will provide x=0.0,y=0.0,z=0.0 if reading is still same for three hours. assume this is starting time of sleep of phone. when reading will change suddenly in terms of x,y,z it will be wake up time.

How can detect this scenario (starting time of sleep & wake up time )?

Below code is detecting gyroscope reading x ,y ,z when it is still it is showing 0.0,0.0,0.0 respectively .

when pic up the phone value of x,y,z increase only So how can we add code to detect time as above scenario.

    import android.app.Activity;
    import android.content.Context;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.widget.TextView;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;

   public class Main extends Activity {
    Dbhelper myDb;
    //variable for x,y,z
    TextView textX, textY, textZ;
Button ButtonView,ButtonAdd;
    TextView text1,text2,text3,text4 ;
    SensorManager sensorManager;
    Sensor sensor;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myDb =new Dbhelper(this);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

        textX = (TextView) findViewById(R.id.textX);
        textY = (TextView) findViewById(R.id.textY);
        textZ = (TextView) findViewById(R.id.textZ);
        text1 = (TextView) findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        text3 = (TextView) findViewById(R.id.text3);
        text4 = (TextView) findViewById(R.id.text4);
        ButtonView=(Button)findViewById(R.id.button_view);
        ButtonAdd=(Button)findViewById(R.id.button_add);
        AddData();
        viewAll();
    }




    public  void AddData() {
        ButtonAdd.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        boolean isInserted = myDb.insertData(text1.getText().toString(), textX.getText().toString(),
                                textY.getText().toString(),
                                textZ.getText().toString());
                        if (isInserted == true)
                            Toast.makeText(Main.this, "Data Inserted", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(Main.this, "Data not Inserted", Toast.LENGTH_LONG).show();
                    }
                }
        );
}

    public void viewAll() {
        ButtonView.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Cursor res = myDb.getAllData();
                        if(res.getCount() == 0) {
                            // show message
                            showMessage("Error","Nothing found");
                            return;
                        }

                        StringBuffer buffer = new StringBuffer();
                        while (res.moveToNext()) {
                            buffer.append("ID :"+ res.getString(0)+"\n");
                            buffer.append("TIME :"+res.getString(1)+"\n");
                            buffer.append("X :"+ res.getString(2)+"\n");
                            buffer.append("Y :"+ res.getString(3)+"\n");
                            buffer.append("Z :"+ res.getString(4)+"\n\n");
                        }
                        // Show all data
                        showMessage("Data",buffer.toString());
                    }
                }
        );
    }

    public void showMessage(String title,String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }

    public void onResume() {
        super.onResume();
        sensorManager.registerListener(gyroListener, sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void onStop() {
        super.onStop();
        sensorManager.unregisterListener(gyroListener);
    }

    public SensorEventListener gyroListener = new SensorEventListener() {
        public void onAccuracyChanged(Sensor sensor, int acc) { }

        public void onSensorChanged(SensorEvent event) {
            long timeStamp = event.timestamp;
            double x = event.values[0];
            x=(double)Math.round(x * 10d) / 10d;
            //x=Math.round(2);
            double y = event.values[1];
            y=(double)Math.round(y * 10d) / 10d;
            double z = event.values[2];
            z=(double)Math.round(z * 10d) / 10d;

            textX.setText("X : " + x );
            textY.setText("Y : " + y );
            textZ.setText("Z : " + z );

            Calendar c2 = Calendar.getInstance();
            SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
            String dateString1 =sdf1.format(c2.getTime());

            int timeOfDay = c2.get(Calendar.HOUR_OF_DAY);
            c2.getTime();




            Calendar c1 = Calendar.getInstance();

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String dateString =sdf.format(c1.getTime());

            int timeOfDay1 = c1.get(Calendar.HOUR_OF_DAY);
            c1.getTime();



            if(timeOfDay >= 11 && timeOfDay <= 20 && x==0 && y==0 && z==0)

                text1.setText("phone is not moving" + dateString);

            else if

                (timeOfDay1 >= 11 && timeOfDay1 <= 20 && x>0 || y>0 || z>0)

                text2.setText("phone is just moved " + dateString1);


            else if(timeOfDay >= 11 && timeOfDay <= 20 )

            text3.setText("Were phone asleep between "+ dateString  + "&" + dateString1);

        }
    };
}

main.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <TextView
        android:id="@+id/textX"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp" 
        android:text="" />
    <TextView
        android:id="@+id/textY"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp" 
        android:textSize="30sp" 
        android:text="" />
    <TextView
        android:id="@+id/textZ"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp" 
        android:textSize="30sp" 
        android:text="" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:textSize="30sp"
        android:text="" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:textSize="30sp"
        android:text="" />

    <TextView
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:textSize="30sp"
        android:text="" />
</LinearLayout>

NOTE: Please don't tell Timestamp is a solution I have already tried.

user6313669
  • 365
  • 2
  • 7
  • 22

2 Answers2

2

In SensorEventListener you can use the callback parameter SensorEvent event to get the timestamp using the below code,

long timeStamp = event.timestamp;

Note: event.timestamp will return long.

EDIT: Updated answer based on your comment.

To check if device hasn't moved for more than three hours, use the below code..

Initialise long lastTimeStamp = 0; in your global variable in your class.

SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                if(Math.round(x) == 0 && Math.round(y) == 0 && Math.round(z) == 0) {
                    //device didn't move - store current timestamp
                    lastTimeStamp = event.timestamp;
                } else {
                    //below if condition is to check if device hasn't been idle 
                    if (lastTimeStamp == 0) {
                        return;
                    }

                    //(3 * 60 * 60 * 1000) checks if device wasn't moved for more than 3 hours
                    if ((event.timestamp - lastTimeStamp) > (3 * 60 * 60 * 1000)) {
                        //code goes here 
                    }
                    lastTimeStamp = 0;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };

Hope this gives more clarity.

Govind
  • 2,482
  • 1
  • 28
  • 40
  • my problem is that i am not getting time when x> 0 y> 0 z> 0 and duration between when x,y,z=0 & x,y,z>0. Unable to display time between this interval.In attached image notice were phone asleep between 13:29:27 & 13:29:27 timer is running either condition is matched or condition is not matched.So unable to detect time interval – user6313669 Jan 12 '17 at 12:37
  • @user6313669 the time difference can be in millisecond or even nanosecond.. you are converting the timestamp to HH:mm:ss, which may not give the difference between the events if they are in millisecond. – Govind Jan 12 '17 at 13:24
  • @user6313669 I have updated the answer. Hope it helps. – Govind Jan 12 '17 at 13:54
  • If we will take float more dynamic data we will get like 0.0021221 so we can't take float. unable to get time suppose phone was idle between 9:01:45 to 12:01:45 .how it will be shown in screen ? – user6313669 Jan 13 '17 at 08:32
  • @user6313669 Math.round() will return the nearest integer value of float. event.values[] return float, hence I've used Math.round() to convert it to int. – Govind Jan 13 '17 at 09:14
  • i have checked for one minute (60 *1000) but unable to print on screen.According to your code if 1 minute device is not moved then should be print but its not printing anything on screen.if ((event.timestamp - lastTimeStamp) > (60 * 1000)) { //code goes here text3.setText("Were phone asleep between "+event.timestamp); } – user6313669 Jan 13 '17 at 10:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/133064/discussion-between-govind-and-user6313669). – Govind Jan 13 '17 at 10:05
1

You can get sensors reading time by sensor.timestamp and use this one instead of getTime()

(Let me correct my mistake here, you can get time by event.timestamp() not sensor.timestamp)

fakturk
  • 415
  • 7
  • 16
  • sensor does not provide timestamp. – Amber Beriwal Jan 12 '17 at 07:53
  • you can get the timestamp with sensor event https://developer.android.com/reference/android/hardware/SensorEvent.html#timestamp – fakturk Jan 12 '17 at 08:55
  • 1
    I agree. `SensorEvent` provides timestamp but not `Sensor`. In above code snippet, `sensor` is an instance of `Sensor`, whereas `event` is an instance of `SensorEvent`. So, it must be `event.timestamp`. – Amber Beriwal Jan 12 '17 at 09:05
  • my problem is that i am not getting time when x> 0 y> 0 z> 0 and duration between when x,y,z=0 & x,y,z>0 – user6313669 Jan 12 '17 at 12:37