Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Android Notification on Desktop

Missed your android device notifications because you were working on your desktop computer/PC? We all would have this problem. No need to worry anymore because we have got an application called Desktop Notifications for Android to solve this problem.

This application gets all your android notifications right on your desktop/PC instantaneously so that you will not miss any of them. This app works with all android application and also have lollipop support.
Desktop notification for android, android device notification, android notification on desktop, get android notifications on your desktop, android notifications on your desktop,

In order to use this extension you need to download and install a free app for your Android device as well as extension for your browser (it supports both chrome and Firefox).

Setting up Desktop Notifications for Android in your desktop/PC





  • Once you have added the extension to your browser, the browser will prompt you to sign in with your Google account.



  • As you get signed in the application will ask you to personalize some settings like notification display time and sound. That’s all for your desktop now head to your android device.



  • Setting up Desktop Notifications for Android in your android device.
  • Head to the play store from your android device and download the application by searching as “Desktop Notifications for Android”.



  • First thing that you have to do as you install and open the application is to enable the desktop notification by clicking the “open notification settings” tab and put a tick over the check box of “desktop notification”.


  •  Then Enable Desktop Notification to OK.


  •  Now you notification access is Enable.



  • Now sign in the application with your Google account.



  • Note: make sure you that use the same Google account for both the desktop and android application.



  • Creating test notification
  • You have finished setting up the application in both the android device and desktop. So let us test it!



  • Click on the create test notification on your android device. As you click it you will get a popup on the bottom right corner of your desktop.

Never miss your notifications again…‘-)
Read More

HTML5 vs. Native vs. Hybrid Mobile : Which Platform is Best

15 Comments
Should you construct mobile apps in native code on every single platform? Would it be a good idea for you to assemble them in hybrid code, like HTML5 application development?

Set in opposition the pros and cons of developing mobile apps natively or with web-based technologies may appear as a useless activity.

HTML5 vs. Native vs. Hybrid Mobile : Which Platform is Best,HTML5 vs. Native vs. Hybrid Mobile,HTML5 vs. Native,Native vs. Hybrid Mobile,Native vs. Hybrid Mobile

The scales measuring every single approach’s qualities and faults never fairly stable in an instantly recognizable way. The technical and operative contrasts between HTML5 application developments vs. Native mobile apps vs. Hybrid mobile application development must be looked wise against particular product objectives and accessible resources.

There are three key ways to develop an application- Native, html5 and hybrid:


  • Native mobile apps can build up using Objective- C for iOS, Java for Android or .NET for Windows for a specific platform.
  • Hybrid mobile application development utilizes HTML5, CSS3 and JavaScript, place in a native package that empowers it to access the device’s hardware. Applications can be constructed by making use tools like Xamarin, PhoneGap and Appcelerator Titanium.
  • Html5 application development/ Web Apps also constructed utilizing HTML5, CSS3 and JavaScript. Similar to mobile sites, it opens in the browsers of mobile. The client need internet availability to get access of the apps and such apps can't be sold on app stores.

How to choose an appropriate mobile Development Tactic?

Toward the day's end, each single business needs to hold the expenses down, without any kind of compromise in quality. To pick a suitable method, we have to recognize all the nitty-gritty concepts of each of them. If we talk about native applications it can deliver the finest work, however you need to construct isolated apps for isolated platforms, and it also cost a lot to develop.

  • If we discuss about hybrid apps VS native apps, hybrid apps cost fewer to develop and a single code performs across diverse platforms, but contact to native APIs can be restricted. Applications constructed by utilizing html5 are very stress-free to develop, but they can't be spread on app stores as well as can't access native APIs and features of device.

The important is to simply outline your potentials from the application you are constructing. The objective of the application, the financial plan, the focused crowd and accessibility of cutting-edge technology will determine your choice.

Go with native mobile app development when you are focusing on only one platform or have sufficient financial plan to construct and maintain applications on three diverse platforms, provide rights to use appropriate tech ability, feel that freely-flowing User Interface is necessary, Need presence on app store, need access to every single native APIs and features of device etc.

  • Follow hybrid apps VS native apps when you need cross platform tools for the app development and you are not able to spend much money on it. If you want to reach to maximum number of users than Hybrid development should be useful to you. If you are not worried about app store deployment than Hybrid app is the best choice. You can easily utilize the expertise of your developers through cross platform tools. App maintenance and support would be simplified with this platform.
  • Choose html5 VS native and hybrid mobile apps, when there is a need of high performance with a single code base to make simpler app maintenance and support. If you want to utilize your particular tech know-how and construct an app in a language of your selection, this platform is best suited to you. There is no requirement to access native APIs and don’t need offline abilities.

A room for Native VS Hybrid VS Html5 app development methodologies

Commonly, full native mobile applications are just inside of bigger associations that can finance early development and current support as well as porting maintenance. Organizations with littler budgets that still need to extend the high quality regarding performance and user experience will also select to go with native since native apps will constantly beat web or hybrid tactics in such manner.
Hybrid apps and Html5 have their own positions as well, VS native applications. They cost less as well as have broader distribution opportunities and are simpler to modify, which is significant benefit for companies that rely on their quickness in rapidly changing markets.

Summing Up

Definitely there is no necessity to go with a particular tactic to the rejection of the others. Compare the cutting-edge technology to the app and advertising necessities, both now and later on, and you would surely find the right fit. Be known for what you love.
Read More

How to Detect Noise in Android

This is a simple example to create an app to detect Noise. When Noise/Sound frequency cross thersold vaule, You will get an alert.

Follow these steps:
1. Create an android project.
2.Create a Main activity (NoiseAlert.java)
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class NoiseAlert extends Activity  {
        /* constants */
        private static final int POLL_INTERVAL = 300;
       
        /** running state **/
        private boolean mRunning = false;
        
        /** config state **/
        private int mThreshold;
        
        private PowerManager.WakeLock mWakeLock;

        private Handler mHandler = new Handler();

        /* References to view elements */
        private TextView mStatusView;
        private SoundLevelView mDisplay;

        /* data source */
        private SoundMeter mSensor;
        
        

     /****************** Define runnable thread again and again detect noise *********/
     
        private Runnable mSleepTask = new Runnable() {
                public void run() {
                    //Log.i("Noise", "runnable mSleepTask");
                        
                    start();
                }
        };
        
        // Create runnable thread to Monitor Voice
        private Runnable mPollTask = new Runnable() {
                public void run() {
                    
                        double amp = mSensor.getAmplitude();
                        //Log.i("Noise", "runnable mPollTask");
                        updateDisplay("Monitoring Voice...", amp);

                        if ((amp > mThreshold)) {
                              callForHelp();
                              //Log.i("Noise", "==== onCreate ===");
                              
                        }
                        
                        // Runnable(mPollTask) will again execute after POLL_INTERVAL
                        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
                     
                }
        };
        
         /*********************************************************/
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                
                // Defined SoundLevelView in main.xml file
                setContentView(R.layout.main);
                mStatusView = (TextView) findViewById(R.id.status);
               
                // Used to record voice
                mSensor = new SoundMeter();
                mDisplay = (SoundLevelView) findViewById(R.id.volume);
                
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "NoiseAlert");
        }

        
        @Override
        public void onResume() {
                super.onResume();
                //Log.i("Noise", "==== onResume ===");
                
                initializeApplicationConstants();
                mDisplay.setLevel(0, mThreshold);
                
                if (!mRunning) {
                    mRunning = true;
                    start();
                }
        }

        @Override
        public void onStop() {
                super.onStop();
               // Log.i("Noise", "==== onStop ===");
               
                //Stop noise monitoring
                stop();
               
        }

        private void start() {
                //Log.i("Noise", "==== start ===");
            
                mSensor.start();
                if (!mWakeLock.isHeld()) {
                        mWakeLock.acquire();
                }
                
                //Noise monitoring start
                // Runnable(mPollTask) will execute after POLL_INTERVAL
                mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }

        private void stop() {
            Log.i("Noise", "==== Stop Noise Monitoring===");
                if (mWakeLock.isHeld()) {
                        mWakeLock.release();
                }
                mHandler.removeCallbacks(mSleepTask);
                mHandler.removeCallbacks(mPollTask);
                mSensor.stop();
                mDisplay.setLevel(0,0);
                updateDisplay("stopped...", 0.0);
                mRunning = false;
               
        }

       
        private void initializeApplicationConstants() {
                // Set Noise Threshold
                mThreshold = 8;
                
        }

        private void updateDisplay(String status, double signalEMA) {
                mStatusView.setText(status);
                //
                mDisplay.setLevel((int)signalEMA, mThreshold);
        }
        
        
        private void callForHelp() {
              
              //stop();
              
             // Show alert when noise thersold crossed
              Toast.makeText(getApplicationContext(), "Noise Thersold Crossed, do here your stuff.",
                      Toast.LENGTH_LONG).show();
        }

};
3.  Create the src/YOUR PACKAGE/SoundLevelView.java and paste following code :
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

class SoundLevelView extends View {
        private Drawable mGreen;
        private Drawable mRed;
        private Paint mBackgroundPaint;
        
        private int mHeight;
        private int mWidth;
        
        private int mThreshold = 0;
        private int mVol = 0;
        
        
        public SoundLevelView(Context context, AttributeSet attrs) {
               super(context, attrs);
 
                mGreen  = context.getResources().getDrawable(
                          R.drawable.greenbar);
                mRed    = context.getResources().getDrawable(
                          R.drawable.redbar);
                
                mWidth  = mGreen.getIntrinsicWidth();
                setMinimumWidth(mWidth*10);
                
                mHeight = mGreen.getIntrinsicHeight();
                setMinimumHeight(mHeight);
                
                //Used to paint canvas background color
                mBackgroundPaint = new Paint();
                mBackgroundPaint.setColor(Color.BLACK);
        
        }
        
        public void setLevel(int volume, int threshold) {
                if (volume == mVol && threshold == mThreshold) return;
                mVol = volume;
                mThreshold = threshold;
                
                // invalidate Call onDraw method and draw voice points
                invalidate();
        }
        
        @Override
        public void onDraw(Canvas canvas) {
               
                canvas.drawPaint(mBackgroundPaint);
               
                for (int i=0; i<= mVol; i++) {
                        Drawable bar;
                        if (i< mThreshold) 
                            bar = mGreen;
                        else           
                            bar = mRed;
 
                        bar.setBounds((10-i)*mWidth, 0, (10-i+1)*mWidth, mHeight);
                        bar.draw(canvas);
                }
        }
}

     SoundLevelView class is used to draw a sound meter on view ( Called in main.xml file ).

4.  Create the src/YOUR PACKAGE/SoundMeter.java  to record noise/sound. and paste following code :
import java.io.IOException;
import android.media.MediaRecorder;

public class SoundMeter {
        // This file is used to record voice
        static final private double EMA_FILTER = 0.6;

        private MediaRecorder mRecorder = null;
        private double mEMA = 0.0;

        public void start() {
               
            if (mRecorder == null) {
                    
                        mRecorder = new MediaRecorder();
                        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                        mRecorder.setOutputFile("/dev/null");
                        
                        try {
                            mRecorder.prepare();
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        
                       mRecorder.start();
                       mEMA = 0.0;
                }
        }
        
        public void stop() {
                if (mRecorder != null) {
                        mRecorder.stop();     
                        mRecorder.release();
                        mRecorder = null;
                }
        }
        
        public double getAmplitude() {
                if (mRecorder != null)
                        return  (mRecorder.getMaxAmplitude()/2700.0);
                else
                        return 0;

        }

        public double getAmplitudeEMA() {
                double amp = getAmplitude();
                mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
                return mEMA;
        }
}

4.  Open  AndroidMainifest.xml : 
     Add Permission
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Thats it.
Note: You can run this apps only on live devices. But before installing this apps on your mobile, Please check the list of sensors running on you mobile
Read More

How to use Light Sensor Android

This is a simple example to create an app using Light Sensor. Here you will learn basics of Light Sensor.

Follow these steps:

1. Create an android project.
2.Create a Main activity (MainLight.java)
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainLight extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor light;
    private TextView text;
    private StringBuilder msg = new StringBuilder(2048);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        light = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
       
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, light, SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, light);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
    msg.insert(0, sensor.getName() + " accuracy changed: " + accuracy +
        (accuracy==1?" (LOW)":(accuracy==2?" (MED)":" (HIGH)")) + "\n");
    text.setText(msg);
    text.invalidate();
  }

  public void onSensorChanged(SensorEvent event) {
    msg.insert(0, "Got a sensor event: " + event.values[0] + " SI lux units\n");
    text.setText(msg);
    text.invalidate();
  }
}
3.  Create the resource res/layout/main.xml and paste following code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"  android:layout_height="fill_parent" >
      <TextView  android:id="@+id/text" android:textSize="20sp"
        android:layout_width="fill_parent"  android:layout_height="wrap_content" />
    </LinearLayout>

 Thats it.
Note: You can run this apps only on live devices. But before installing this apps on your mobile, Please check the list of sensors running on you mobile

Read More

How to use Gyroscope Sensor in Android

This is a simple example to create an app using Gyroscope Sensor. Here you will learn basics of Gyroscope Sensor.

Follow these steps:

1. Create an android project.
2.Create a Main activity (MainGyroscope.java)
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainGyroscope extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor gyro;
    private TextView text;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        gyro = mgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, gyro, SensorManager.SENSOR_DELAY_GAME);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, gyro);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  public void onSensorChanged(SensorEvent event) {
    String msg = "0: " + event.values[0] + "\n" +
        "1: " + event.values[1] + "\n" +
        "2: " + event.values[2] + "\n";
    text.setText(msg);
    text.invalidate();
  }
}

3.  Create the resource res/layout/main.xml and paste following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  android:layout_height="fill_parent" >
  <TextView  android:id="@+id/text" android:textSize="20sp"
    android:layout_width="fill_parent"  android:layout_height="wrap_content" />
</LinearLayout>
 Thats it.
Note: You can run this apps only on live devices. But before installing this apps on your mobile, Please check the list of sensors running on you mobile.
Read More

How to use Accelerometer in Android

Basic example of Accelerometer: How to Detect Phone Shake Motion
When Accelerometer force value cross thersold showing an alert for motion detected.
Follow these steps to create an app:
1. Create a Main activity (MainAccelerometer.java):

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

public class MainAccelerometer extends Activity implements AccelerometerListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accelerometer_example_main);
        
        // Check onResume Method to start accelerometer listener
    }
   
    public void onAccelerationChanged(float x, float y, float z) {
        // TODO Auto-generated method stub
        
    }

    public void onShake(float force) {
        
        // Do your stuff here
        
        // Called when Motion Detected
        Toast.makeText(getBaseContext(), "Motion detected",
                Toast.LENGTH_SHORT).show();
        
    }

    @Override
    public void onResume() {
            super.onResume();
            Toast.makeText(getBaseContext(), "onResume Accelerometer Started",
                    Toast.LENGTH_SHORT).show();
            
            //Check device supported Accelerometer senssor or not
            if (AccelerometerManager.isSupported(this)) {
                
                //Start Accelerometer Listening
                AccelerometerManager.startListening(this);
            }
    }
    
    @Override
    public void onStop() {
            super.onStop();
            
            //Check device supported Accelerometer senssor or not
            if (AccelerometerManager.isListening()) {
                
                //Start Accelerometer Listening
                AccelerometerManager.stopListening();
                
                Toast.makeText(getBaseContext(), "onStop Accelerometer Stoped",
                         Toast.LENGTH_SHORT).show();
            }
           
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("Sensor", "Service  distroy");
        
        //Check device supported Accelerometer senssor or not
        if (AccelerometerManager.isListening()) {
            
            //Start Accelerometer Listening
            AccelerometerManager.stopListening();
            
            Toast.makeText(getBaseContext(), "onDestroy Accelerometer Stoped",
                   Toast.LENGTH_SHORT).show();
        }
            
    }

}
When you create this page, You will get an error due to missing of AccelerometerListener interface.
So, Next create an interface...

2  src/AccelerometerListener.java

      public interface AccelerometerListener {
     
    public void onAccelerationChanged(float x, float y, float z);
 
    public void onShake(float force);
 
      }


3 src/AccelerometerManager.java
import java.util.List;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.Toast;

public class AccelerometerManager {
 
    private static Context aContext=null;
    
    
    /** Accuracy configuration */
    private static float threshold  = 15.0f;
    private static int interval     = 200;
 
    private static Sensor sensor;
    private static SensorManager sensorManager;
    // you could use an OrientationListener array instead
    // if you plans to use more than one listener
    private static AccelerometerListener listener;
 
    /** indicates whether or not Accelerometer Sensor is supported */
    private static Boolean supported;
    /** indicates whether or not Accelerometer Sensor is running */
    private static boolean running = false;
 
    /**
     * Returns true if the manager is listening to orientation changes
     */
    public static boolean isListening() {
        return running;
    }
 
    /**
     * Unregisters listeners
     */
    public static void stopListening() {
        running = false;
        try {
            if (sensorManager != null && sensorEventListener != null) {
                sensorManager.unregisterListener(sensorEventListener);
            }
        } catch (Exception e) {}
    }
 
    /**
     * Returns true if at least one Accelerometer sensor is available
     */
    public static boolean isSupported(Context context) {
        aContext = context;
        if (supported == null) {
            if (aContext != null) {
                
                
                sensorManager = (SensorManager) aContext.
                        getSystemService(Context.SENSOR_SERVICE);
                
                // Get all sensors in device
                List<Sensor> sensors = sensorManager.getSensorList(
                        Sensor.TYPE_ACCELEROMETER);
                
                supported = new Boolean(sensors.size() > 0);
                
                
                
            } else {
                supported = Boolean.FALSE;
            }
        }
        return supported;
    }
 
    /**
     * Configure the listener for shaking
     * @param threshold
     *             minimum acceleration variation for considering shaking
     * @param interval
     *             minimum interval between to shake events
     */
    public static void configure(int threshold, int interval) {
        AccelerometerManager.threshold = threshold;
        AccelerometerManager.interval = interval;
    }
 
    /**
     * Registers a listener and start listening
     * @param accelerometerListener
     *             callback for accelerometer events
     */
    public static void startListening( AccelerometerListener accelerometerListener )
    {
        
        sensorManager = (SensorManager) aContext.
                getSystemService(Context.SENSOR_SERVICE);
        
        // Take all sensors in device
        List<Sensor> sensors = sensorManager.getSensorList(
                Sensor.TYPE_ACCELEROMETER);
        
        if (sensors.size() > 0) {
            
            sensor = sensors.get(0);
            
            // Register Accelerometer Listener
            running = sensorManager.registerListener(
                    sensorEventListener, sensor,
                    SensorManager.SENSOR_DELAY_GAME);
            
            listener = accelerometerListener;
        }
        
        
    }
 
    /**
     * Configures threshold and interval
     * And registers a listener and start listening
     * @param accelerometerListener
     *             callback for accelerometer events
     * @param threshold
     *             minimum acceleration variation for considering shaking
     * @param interval
     *             minimum interval between to shake events
     */
    public static void startListening(
            AccelerometerListener accelerometerListener,
            int threshold, int interval) {
        configure(threshold, interval);
        startListening(accelerometerListener);
    }
 
    /**
     * The listener that listen to events from the accelerometer listener
     */
    private static SensorEventListener sensorEventListener =
        new SensorEventListener() {
 
        private long now = 0;
        private long timeDiff = 0;
        private long lastUpdate = 0;
        private long lastShake = 0;
 
        private float x = 0;
        private float y = 0;
        private float z = 0;
        private float lastX = 0;
        private float lastY = 0;
        private float lastZ = 0;
        private float force = 0;
 
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
 
        public void onSensorChanged(SensorEvent event) {
            // use the event timestamp as reference
            // so the manager precision won't depends
            // on the AccelerometerListener implementation
            // processing time
            now = event.timestamp;
 
            x = event.values[0];
            y = event.values[1];
            z = event.values[2];
 
            // if not interesting in shake events
            // just remove the whole if then else block
            if (lastUpdate == 0) {
                lastUpdate = now;
                lastShake = now;
                lastX = x;
                lastY = y;
                lastZ = z;
                Toast.makeText(aContext,"No Motion detected",
                   Toast.LENGTH_SHORT).show();
                
            } else {
                timeDiff = now - lastUpdate;
               
                if (timeDiff > 0) {
                    
                    /*force = Math.abs(x + y + z - lastX - lastY - lastZ)
                                / timeDiff;*/
                    force = Math.abs(x + y + z - lastX - lastY - lastZ);
                    
                    if (Float.compare(force, threshold) >0 ) {
                        //Toast.makeText(Accelerometer.getContext(),
                        //(now-lastShake)+"  >= "+interval, 1000).show();
                        
                        if (now - lastShake >= interval) {
                            
                            // trigger shake event
                            listener.onShake(force);
                        }
                        else
                        {
                            Toast.makeText(aContext,"No Motion detected",
                                Toast.LENGTH_SHORT).show();
                            
                        }
                        lastShake = now;
                    }
                    lastX = x;
                    lastY = y;
                    lastZ = z;
                    lastUpdate = now;
                }
                else
                {
                    Toast.makeText(aContext,"No Motion detected", Toast.LENGTH_SHORT).show();
                    
                }
            }
            // trigger change event
            listener.onAccelerationChanged(x, y, z);
        }
 
    };
 
}
 In this class define functions to start acclerometer sensor related functions like.. Check for acclerometer sensor,start acclerometer sensor,stop acclerometer sensor.

4.  Add following code in AndroidMainifest.xml just above </manifest>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
 5. Create the resource res/layout/ accelerometer_example_main.xml and paste following code

<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"
    tools:context=".MainAccelerometer" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Shake / Tilt Your Phone To Get Accelerometer Motion Alerts" />

</RelativeLayout>

That's it.
Note: You can test this app on real devices only

Read More

How to find list of sensors built in you android mobile.

I am going to teach you. How can you create an apps that displays all the sensors in the phone reporting the following characteristics:
  1. Name: Name of the sensor
  2. Version: Version of the sensor’s module
  3. Vendor: Vendor of this sensor
  4. Type: Type of this sensor
  5. Max Range: maximum range of the sensor
  6. Resolution: resolution of the sensor
  7. Min Delay: minimum delay allowed between two events (equals to zero if this sensor only returns a value when the data it’s measuring changes)
  8. Power: the power of the sensor
Lets start to develop this app. Follow these steps:
  1. Create a project.
  2. Open file res/values/strings.xml and replace all content with following:
<resources>
    <string name="app_name">Sensor List</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="name_label">Name</string>
    <string name="vendor_label">Vendor</string>
    <string name="default_text">not found</string>
    <string name="type_label">Type</string>
    <string name="version_label">Version</string>
    <string name="maximum_range_label">Max Range</string>
    <string name="min_delay_label">Min Delay</string>
    <string name="resolution_label">Resolution</string>
    <string name="power_label">Power</string>
</resources>
             These string name, we will use in entire project.

      3.  Now create the file res/values/types.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="accelerometer">accelerometer sensor</string>
    <string name="ambient_temperature">ambient temperature sensor</string>
    <string name="gravity">gravity sensor</string>
    <string name="gyroscope">gyroscope sensor</string>
    <string name="light">light sensor</string>
    <string name="linear_acceleration">linear acceleration sensor</string>
    <string name="magnetic_field">magnetic field sensor</string>
    <string name="orientation">orientation sensor (deprecated)</string>
    <string name="pressure">pressure sensor</string>
    <string name="proximity">proximity sensor</string>
    <string name="relative_humidity">relative humidity sensor</string>
    <string name="rotation_vector">rotation vector sensor</string>
    <string name="temperature">temperature sensor (deprecated)</string>
    <string name="unknown">unknown sensor</string>
</resources>
      4.  Open the file res/values/styles.xml  and replace with following code:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

 <style name="AppTheme" parent="android:Theme.Light" />

 <style
  name="TitleLabel"
  parent="@android:style/Widget.TextView">
  <item name="android:textStyle">italic</item>
  <item name="android:textSize">14sp</item>
 </style>

 <style
  name="BodyLabel"
  parent="@android:style/Widget.TextView">
  <item name="android:textStyle">italic</item>
  <item name="android:textSize">12sp</item>
 </style>

 <style
  name="TitleView"
  parent="@android:style/Widget.TextView">
  <item name="android:textStyle">bold</item>
  <item name="android:textSize">14sp</item>
 </style>

 <style
  name="BodyView"
  parent="@android:style/Widget.TextView">
  <item name="android:textSize">12sp</item>
 </style>

</resources>
  5. There are many sensors using in your mobile. To view all sensors in a list. Create  the resource res/layout/list_item.xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10sp"
        android:paddingBottom="10sp" >

        <TextView
            android:id="@+id/nameLabel"
            style="@style/TitleLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp"
            android:text="@string/name_label" />

        <TextView
            android:id="@+id/vendorLabel"
            style="@style/TitleLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/nameLabel"
            android:layout_below="@id/nameLabel"
            android:text="@string/vendor_label" />

        <TextView
            android:id="@+id/typeLabel"
            style="@style/BodyLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/vendorLabel"
            android:layout_below="@id/vendorLabel"
            android:text="@string/type_label" />

        <TextView
            android:id="@+id/maximumRangeLabel"
            style="@style/BodyLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/typeLabel"
            android:layout_below="@id/typeLabel"
            android:text="@string/maximum_range_label" />

        <TextView
            android:id="@+id/resolutionLabel"
            style="@style/BodyLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/maximumRangeLabel"
            android:layout_below="@id/maximumRangeLabel"
            android:text="@string/resolution_label" />

        <TextView
            android:id="@+id/minDelayLabel"
            style="@style/BodyLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/resolutionLabel"
            android:layout_below="@id/resolutionLabel"
            android:text="@string/min_delay_label" />

        <TextView
            android:id="@+id/powerLabel"
            style="@style/BodyLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/minDelayLabel"
            android:layout_below="@id/minDelayLabel"
            android:text="@string/power_label" />

        <TextView
            android:id="@+id/nameView"
            style="@style/TitleView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/nameLabel"
            android:layout_alignBottom="@id/nameLabel"
            android:layout_marginLeft="40dp"
            android:layout_toRightOf="@id/nameLabel"
            android:singleLine="true"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/versionLabel"
            style="@style/BodyLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/nameView"
            android:layout_alignBottom="@id/nameView"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/nameView"
            android:text="@string/version_label" />

        <TextView
            android:id="@+id/vendorView"
            style="@style/TitleView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/vendorLabel"
            android:layout_alignBottom="@id/vendorLabel"
            android:layout_alignLeft="@id/nameView"
            android:singleLine="true"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/typeView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/typeLabel"
            android:layout_alignBottom="@id/typeLabel"
            android:layout_alignLeft="@id/nameView"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/versionView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/versionLabel"
            android:layout_alignBottom="@id/versionLabel"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/versionLabel"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/maximumRangeView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/maximumRangeLabel"
            android:layout_alignBottom="@id/maximumRangeLabel"
            android:layout_alignLeft="@id/nameView"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/unitsRangeView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/maximumRangeView"
            android:layout_alignBottom="@id/maximumRangeView"
            android:layout_marginLeft="2dp"
            android:layout_toRightOf="@id/maximumRangeView"
            android:text="" />

        <TextView
            android:id="@+id/minDelayView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/minDelayLabel"
            android:layout_alignBottom="@id/minDelayLabel"
            android:layout_alignLeft="@id/nameView"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/unitsDelayView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/minDelayView"
            android:layout_alignBottom="@id/minDelayView"
            android:layout_marginLeft="2dp"
            android:layout_toRightOf="@id/minDelayView"
            android:text="" />

        <TextView
            android:id="@+id/powerView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/powerLabel"
            android:layout_alignBottom="@id/powerLabel"
            android:layout_alignLeft="@id/nameView"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/unitsPowerView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/powerView"
            android:layout_alignBottom="@id/powerView"
            android:layout_marginLeft="2dp"
            android:layout_toRightOf="@id/powerView"
            android:text="" />

        <TextView
            android:id="@+id/resolutionView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/resolutionLabel"
            android:layout_alignBottom="@id/resolutionLabel"
            android:layout_alignLeft="@id/nameView"
            android:text="@string/default_text" />

        <TextView
            android:id="@+id/unitsResolutionView"
            style="@style/BodyView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/resolutionView"
            android:layout_alignBottom="@id/resolutionView"
            android:layout_marginLeft="2dp"
            android:layout_toRightOf="@id/resolutionView"
            android:text="" />

    </RelativeLayout>

</HorizontalScrollView>

    You have created all xml files required to display contents . Now its time to play with Java coding to make this apps live.

     6.   Open your MainActivity.java page (Check in src\YOUR PACKAGE\)     and replace all content with following content except first line (indicating import your package)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class MainActivity extends ListActivity implements SensorEventListener {

    private SensorAdapter adapter;
    private List<MySensor> sensorList;

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sensorList = new ArrayList<MySensor>(); /* It is an array containing the Sensor objects that are the sensors of the phone */
    sensorList = getSensors();
    adapter = new SensorAdapter(this, R.layout.list_item, sensorList);
    setListAdapter(adapter);
    }

    public void onSensorChanged(SensorEvent event) {
    }

    private List<MySensor> getSensors() {    /*I find all the sensors of the phone and I add them as objects of the class MySensor to a List that I set to ArrayList<MySensor> in the onCreate event*/

    List<MySensor> list = new ArrayList<MySensor>();

    SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> phoneSensor = sm.getSensorList(Sensor.TYPE_ALL);

    Iterator<Sensor> it = phoneSensor.iterator();
    while (it.hasNext()) {
        Sensor s = it.next();
        list.add(new MySensor(s, getApplicationContext()));
    }

    return list;
    }
}

Check this line: public class MainActivity extends ListActivity implements SensorEventListener
Here MainActivity is extended by ListActivity. Because it's easy to show contents in list view using ListActivity.

7.   Create SensorAdapter.java class on same folder where your MainActivity.java file stored.
8.   Open this page. Copy following content and paste it.
      import java.util.List;

import android.content.Context;
import android.os.Build;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SensorAdapter extends ArrayAdapter<MySensor> {

    private static final int SDK = Build.VERSION.SDK_INT;
    private int resource;

    public SensorAdapter(Context context, int resource, List<MySensor> items) {
    super(context, resource, items);
    this.resource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout newView;

    if (convertView == null) {
        newView = new LinearLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li;
        li = (LayoutInflater) getContext().getSystemService(inflater);
        li.inflate(resource, newView, true);
    } else {
        newView = (LinearLayout) convertView;
    }

    TextView nameView = (TextView) newView.findViewById(R.id.nameView);
    TextView vendorView = (TextView) newView.findViewById(R.id.vendorView);
    TextView typeView = (TextView) newView.findViewById(R.id.typeView);
    TextView versionView = (TextView) newView
        .findViewById(R.id.versionView);
    TextView maximumRangeView = (TextView) newView
        .findViewById(R.id.maximumRangeView);
    TextView minDelayView = (TextView) newView
        .findViewById(R.id.minDelayView);
    TextView powerView = (TextView) newView.findViewById(R.id.powerView);
    TextView resolutionView = (TextView) newView
        .findViewById(R.id.resolutionView);
    TextView unitsRangeView = (TextView) newView
        .findViewById(R.id.unitsRangeView);
    TextView unitsResolutionView = (TextView) newView
        .findViewById(R.id.unitsResolutionView);
    TextView unitsDelayView = (TextView) newView
        .findViewById(R.id.unitsDelayView);
    TextView unitsPowerView = (TextView) newView
        .findViewById(R.id.unitsPowerView);

    if (SDK < Build.VERSION_CODES.GINGERBREAD) {
        TextView minDelayLabel = (TextView) newView
            .findViewById(R.id.minDelayLabel);
        minDelayLabel.setVisibility(View.GONE);
        minDelayView.setVisibility(View.GONE);
        unitsDelayView.setVisibility(View.GONE);
    }

    MySensor mySensor = getItem(position);

    nameView.setText(mySensor.getName());
    vendorView.setText(mySensor.getVendor());
    typeView.setText(mySensor.getTypeDescription());
    versionView.setText(String.valueOf(mySensor.getVersion()));
    maximumRangeView.setText(String.valueOf(mySensor.getMaximumRange()));
    if (SDK >= Build.VERSION_CODES.GINGERBREAD)
        minDelayView.setText(String.valueOf(mySensor.getMinDelay()));
    powerView.setText(String.valueOf(mySensor.getPower()));
    resolutionView.setText(String.format("%f", mySensor.getResolution()));
    unitsRangeView.setText(Html.fromHtml(mySensor.getUnits()));
    unitsResolutionView.setText(Html.fromHtml(mySensor.getUnits()));
    if (SDK >= Build.VERSION_CODES.GINGERBREAD)
        unitsDelayView.setText(Html.fromHtml(mySensor.getDelayUnits()));
    unitsPowerView.setText(Html.fromHtml(mySensor.getPowerUnits()));

    return newView;

    }
}
 When you extend an ArrayAdapter, you override the method getView to set the layout (res/layout/list_item.xml)
I display and set the text views related to “Min Delay” only if the API level is equal to or greater than Gingerbread
some strings are displayed using the method Html.fromHtml(String source) because they contain special characters (µ or ²).

  9.  Create a class MySensor.java  on same package where MainActivity.java class stored. Copy following content and paste into MySensor.java class.
import android.annotation.TargetApi;
import android.content.Context;
import android.hardware.Sensor;
import android.os.Build;

public class MySensor {

    private final static String MICRO = "&amp;#x3BC;";
    private static final int SDK = Build.VERSION.SDK_INT;
    private final static String SQUARE = "&amp;#xB2;";
    private Context context;
    private float maximumRange, minDelay, power, resolution;
    private String name, vendor;
    private int type, version;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public MySensor(Sensor sensor, Context context) {
    this.name = sensor.getName();
    this.vendor = sensor.getVendor();
    this.type = sensor.getType();
    this.version = sensor.getVersion();
    this.maximumRange = sensor.getMaximumRange();
    if (SDK >= Build.VERSION_CODES.GINGERBREAD)
        this.minDelay = sensor.getMinDelay();
    this.power = sensor.getPower();
    this.resolution = sensor.getResolution();
    this.context = context;
    }

    public String getDelayUnits() {
    return MICRO + "s";
    }

    public float getMaximumRange() {
    return maximumRange;
    }

    public float getMinDelay() {
    return minDelay;
    }

    public String getName() {
    return name;
    }

    public float getPower() {
    return power;
    }

    public String getPowerUnits() {
    return "mA";
    }

    public float getResolution() {
    return resolution;
    }

    public int getType() {
    return type;
    }

    public String getTypeDescription() {
    String description = null;

    switch (type) {
    case Sensor.TYPE_ACCELEROMETER:
        description = context.getResources().getString(
            R.string.accelerometer);
        break;
    case Sensor.TYPE_AMBIENT_TEMPERATURE:
        description = context.getResources().getString(
            R.string.ambient_temperature);
        break;
    case Sensor.TYPE_GRAVITY:
        description = context.getResources().getString(R.string.gravity);
        break;
    case Sensor.TYPE_GYROSCOPE:
        description = context.getResources().getString(R.string.gyroscope);
        break;
    case Sensor.TYPE_LIGHT:
        description = context.getResources().getString(R.string.light);
        break;
    case Sensor.TYPE_LINEAR_ACCELERATION:
        description = context.getResources().getString(
            R.string.linear_acceleration);
        break;
    case Sensor.TYPE_MAGNETIC_FIELD:
        description = context.getResources().getString(
            R.string.magnetic_field);
        break;
    case Sensor.TYPE_ORIENTATION:
        description = context.getResources()
            .getString(R.string.orientation);
        break;
    case Sensor.TYPE_PRESSURE:
        description = context.getResources().getString(R.string.pressure);
        break;
    case Sensor.TYPE_PROXIMITY:
        description = context.getResources().getString(R.string.proximity);
        break;
    case Sensor.TYPE_RELATIVE_HUMIDITY:
        description = context.getResources().getString(
            R.string.relative_humidity);
        break;
    case Sensor.TYPE_ROTATION_VECTOR:
        description = context.getResources().getString(
            R.string.rotation_vector);
        break;
    case Sensor.TYPE_TEMPERATURE:
        description = context.getResources()
            .getString(R.string.temperature);
        break;
    default:
        description = context.getResources().getString(R.string.unknown);
        break;
    }

    return description;
    }

    public String getUnits() {
    String units = null;

    switch (type) {
    case Sensor.TYPE_ACCELEROMETER:
        units = "m/s" + SQUARE;
        break;
    case Sensor.TYPE_AMBIENT_TEMPERATURE:
        units = "°C";
        break;
    case Sensor.TYPE_GRAVITY:
        units = "m/s" + SQUARE;
        break;
    case Sensor.TYPE_GYROSCOPE:
        units = "rad/s";
        break;
    case Sensor.TYPE_LIGHT:
        units = "SI lux";
        break;
    case Sensor.TYPE_LINEAR_ACCELERATION:
        units = "m/s" + SQUARE;
        break;
    case Sensor.TYPE_MAGNETIC_FIELD:
        units = MICRO + "T";
        break;
    case Sensor.TYPE_ORIENTATION:
        units = "°";
        break;
    case Sensor.TYPE_PRESSURE:
        units = "hPa";
        break;
    case Sensor.TYPE_PROXIMITY:
        units = "cm";
        break;
    case Sensor.TYPE_RELATIVE_HUMIDITY:
        units = "";
        break;
    case Sensor.TYPE_ROTATION_VECTOR:
        units = "";
        break;
    case Sensor.TYPE_TEMPERATURE:
        units = "°C";
        break;
    default:
        units = "unknown";
        break;
    }

    return units;
    }

    public String getVendor() {
    return vendor;
    }

    public int getVersion() {
    return version;
    }

    public void setMaximumRange(float maximumRange) {
    this.maximumRange = maximumRange;
    }

    public void setMinDelay(float minDelay) {
    this.minDelay = minDelay;
    }

    public void setName(String name) {
    this.name = name;
    }

    public void setPower(float power) {
    this.power = power;
    }

    public void setResolution(float resolution) {
    this.resolution = resolution;
    }

    public void setType(int type) {
    this.type = type;
    }

    public void setVendor(String vendor) {
    this.vendor = vendor;
    }

    public void setVersion(int version) {
    this.version = version;
    }

    @Override
    public String toString() {
    return name;
    }

}
The method getMinDelay of the class Sensor is new with GingerBread (API 9, Android 2.3), then you can use it only after the condition that the API level of the device is equal to or greater than 9
the annotation @TargetApi avoids a compilation error
the variables MICRO e SQUARE define some special characters in the method Html.fromHtml(String source) of the class SensorAdapte.


Read More