Accelerometer (Shake Events) Example with Service Android.

Hello Friends,

This tutorial is about get shake event when you are not in Application or any specific activity.

With the help of Service we can get Shake Event out of activity.

First of We will create class which extends Service and Implements SensorEventListener.

1. Class  MyService.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.ammy.shakeevent.R;

public class MyService extends Service implements SensorEventListener {

	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	private float mAccel; // acceleration apart from gravity
	private float mAccelCurrent; // current acceleration including gravity
	private float mAccelLast; // last acceleration including gravity

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_UI, new Handler());
		return START_STICKY;
	}

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

	@Override
	public void onSensorChanged(SensorEvent event) {
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		mAccelLast = mAccelCurrent;
		mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
		float delta = mAccelCurrent - mAccelLast;
		mAccel = mAccel * 0.9f + delta; // perform low-cut filter

		if (mAccel > 11) {
			showNotification();
		}
	}

	/**
	 * show notification when Accel is more then the given int.
	 */
	private void showNotification() {
		final NotificationManager mgr = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationCompat.Builder note = new NotificationCompat.Builder(this);
		note.setContentTitle("Device Accelerometer Notification");
		note.setTicker("New Message Alert!");
		note.setAutoCancel(true);
		// to set default sound/light/vibrate or all
		note.setDefaults(Notification.DEFAULT_ALL);
		// Icon to be set on Notification
		note.setSmallIcon(R.drawable.ic_launcher);
		// This pending intent will open after notification click
		PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
				MainActivity.class), 0);
		// set pending intent to notification builder
		note.setContentIntent(pi);
		mgr.notify(101, note.build());
	}
}








In onStartCommand it returns START_STICKY. START_STICKY leave service in the started state.


2. MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ammy.shakeevent.R;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent intent = new Intent(this, MyService.class);
		//Start Service
		startService(intent);
	}

}

3. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ammy.shakeevent"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.VIBRATE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ammy.shakeevent.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.ammy.shakeevent.MyService"></service>
    </application>

</manifest>

Points to Remember:- 1. Set permission of Vibrate for vibration on notification. 2. Register Service in AndroidManifest.xml. 



Refrences:- http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/reference/android/hardware/SensorManager.html

You can download the demo source code from here.

happy blogging.. :D

Comments

Popular posts from this blog

How to combine two Bitmap in Android

How to change the color of Hamburger icon in Toolbar Android

How to do Facebook Login with Custom Button Android