Friday, February 10, 2017

Measuring earth gravity using android phone source code

Following is the complete source code for earth gravity measurement app :
activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:paddingBottom="@dimen/activity_vertical_margin"    
android:paddingLeft="@dimen/activity_horizontal_margin"    
android:paddingRight="@dimen/activity_horizontal_margin"    
android:paddingTop="@dimen/activity_vertical_margin"    
tools:context="com.example.naveenj.sensor.MainActivity">
<TextView        
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:textAppearance="?android:attr/textAppearanceLarge"        
android:text="Large Text"        
android:id="@+id/textView"        
android:layout_marginLeft="75dp"        
android:layout_marginStart="75dp"        
android:layout_marginTop="131dp" />
</RelativeLayout>


This just contains a TextView where we printout the sensor output.

MainActivity.Java :


package com.example.naveenj.sensor;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener{

    Sensor acc;
    SensorManager sm;
    TextView t;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sm = (SensorManager)getSystemService(SENSOR_SERVICE);
        acc = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sm.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL);
        t = (TextView)findViewById(R.id.textView);
    }

    @Override    public void onSensorChanged(SensorEvent event) {
        t.setText("X: "+event.values[0]+"Y" + event.values[1]+"z"+
                     event.values[2]+event.toString());
    }

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

    }
}

MainActivity class implements the interface SensorEventListener. 
This interface has 2 function : 
 1) onSensorChanged
 2) onAccuracyChanged

we then register our main activity class to receive events from sensor 
using SensorManager.

when placed idle phone's z-axis will show earth's gravity.
  

No comments:

Post a Comment