Integrate Facebook App Id and Secret Key into Parse

Integrate Facebook App Id and Secret Key into Parse

If you have account on Parse than follow step6 or start from beginning. Step1: SignUp in to Parse.com, here is a link for signup into parse https://www.parse.com/#signup.

Integrate Facebook App Id and Secret Key into Parse

Step2: Enter Your App Name and click on “Create App”

Integrate Facebook App Id and Secret Key into Parse

Step3: After creating app you will get you Application Key.

Integrate Facebook App Id and Secret Key into Parse

If you can not find your application and client key than go to “Dashboard” and click on “Select an App”

Integrate Facebook App Id and Secret Key into Parse
Integrate Facebook App Id and Secret Key into Parse

Step4: Now click on “Setting” and than “Key” here you can get every key that is related to your app

Integrate Facebook App Id and Secret Key into Parse

Step5: Here you can get your Application Key and Client Key.

Register Facebook Key Into Parse

Step6:click on “Authentication” and check “Allow Facebook authentication” , make it “YES”.

Enter your facebook App id and secret key.
Integrate Facebook App Id and Secret Key into Parse

Now you can use parse into your project with facebook account.

Get Facebook App Id

Get Facebook App Id

Before you start to generate Facebook App id. Take a look on facebook development.

Facebook allows you to obtain a token to access Facebook’s API on behalf of someone using your app. You can use this feature in place of building your own account system or to add Facebook services to your existing accounts.The Facebook SDK for Android provides methods to implement Facebook Login for your app. And to access this feature into your app you need facebook app id.

Now start to generate facebbok id , you should need a facebook account as a developer or you can use your personal account also. Step1: Goto facebook developer site and login.

Here is facebook developer link

https://developers.facebook.com/apps

open this and login to developer account.

Get Facebook App Id

Step2:click on “Add a New App” and than select your app platform, here we are using Android so click on “Android”.

Get Facebook App Id

Step3:Now click on “Create App Id” enter your app details and finally click on ”Create App Id”

Get Facebook App Id

Step4: Your Facebook App Id is generated, copy this app id and used for your app development.

Get Facebook App Id

Step5: If you need facebook app secret key than click on “show” button and you will get your secret key.

Get Parse App Key and Client Key

Get Parse App Key and Client Key

Before you start to generate Parse APP_KEY and CLIENT_KEY did you know what is Parse? Ok take a overview of Parse than we will start.

What is Parse?

Parse.com provides a backend service to developers. If your mobile or desktop app requires a backend on the internet, then Parse is one of the options you can choose.

I first came across the service a few months ago and noted that they provide SDKs that let your apps running on various devices connect up to the backend it provides. They provide SDKs for devices running iOS, Android, Windows (Phone) 8, OS X and Javascript.

ok now start generating Parse KEY. Step1: SignUp in to Parse.com, here is a link for signup into parse https://www.parse.com/#signup.

Get Parse App Key and Client Key

Step2:Enter Your App Name and click on “Create App”

Get Parse App Key and Client Key

Step3: After creating app you will get you Application Key.

Get Parse App Key and Client Key

If you can not find your application and client key than go to “Dashboard” and click on “Select an App”

Get Parse App Key and Client Key
Get Parse App Key and Client Key

Step4: Now click on Setting and than Key here you can get every key that is related to your app

Get Parse App Key and Client Key

Step5: Here you can get your Application Key and Client Key.

Android App for detecting WiFi Signal (with Source Code)

Android App for detecting WiFi Signal (with Source Code)

Download APK Download Source Code Contact Us

Wifi Android project based on Wi-Fi APIs provide a means by which applications can communicate with the lower-level wireless stack that provides Wi-Fi network access. Almost all information from the device supplicant is available, including the connected network’s link speed, IP address, negotiation state, and more, plus information about other networks that are available.

WifiManager class provides the primary API for managing all aspects of Wi-Fi connectivity.

About Android App:

Android operating system is the fast growing mobile operating system in the market. Android provides solution for users to develop their own apps and upload to app store and help users to download for free of cost.

Layout Code: activity_main. Xml
When application is executed this is the first layout design that will run which will load width, height, load back ground details..etc.

<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:background="#000000"
    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=".MainActivity" >

    <Button android:id="@+id/btn_wifi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="OFF"></Button>

    <ListView android:id="@+id/list_view_wifi"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/btn_wifi" >
    </ListView>

</RelativeLayout>

Layout Code: single_list. Xml
This xml file for single item view of list.


<LinearLayout 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" >

    <TextView android:id="@+id/txt_wifi_provider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:textSize="16dp"
        android:textStyle="bold"></TextView>

</LinearLayout>

Java File : MainActivity.java
MainActivity.java file in package com.mobilemerit.wifi.
Main activity file will load design form like buttons, text view, on click functionality, display text.

package com.mobilemerit.wifi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.mobilemerit.adapter.ListAdapter;
import com.mobilemerit.javafiles.ImportDialog;
import com.mobilemerit.wifi.R;

public class MainActivity extends Activity implements OnClickListener {
	Button setWifi;
	WifiManager wifiManager;
	WifiReceiver receiverWifi;
	List<scanresult> wifiList;
	List<string> listOfProvider;
	ListAdapter adapter;
	ListView listViwProvider;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		listOfProvider = new ArrayList</string><string>();
		
		/*setting the resources in class*/
		listViwProvider = (ListView) findViewById(R.id.list_view_wifi);
		setWifi = (Button) findViewById(R.id.btn_wifi);
		
		setWifi.setOnClickListener(this);
		wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		/*checking wifi connection
		 * if wifi is on searching available wifi provider*/ 
		if (wifiManager.isWifiEnabled() == true) {
			setWifi.setText("ON");
			scaning();
		}
		/*opening a detail dialog of provider on click   */
		listViwProvider.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView< ?> parent, View view,
					int position, long id) {
					ImportDialog action = new ImportDialog(MainActivity.this, (wifiList.get(position)).toString());
					action.showDialog();
			}
		});
	}

	private void scaning() {
		// wifi scaned value broadcast receiver
		receiverWifi = new WifiReceiver();
		// Register broadcast receiver
		// Broacast receiver will automatically call when number of wifi
		// connections changed
		registerReceiver(receiverWifi, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		wifiManager.startScan();
		
	}

	/*setting the functionality of ON/OFF button*/
	@Override
	public void onClick(View arg0) {
		/* if wifi is ON set it OFF and set button text "OFF" */
		if (wifiManager.isWifiEnabled() == true) {
			wifiManager.setWifiEnabled(false);
			setWifi.setText("OFF");
			listViwProvider.setVisibility(ListView.GONE);
		} 
		/* if wifi is OFF set it ON 
		 * set button text "ON" 
		 * and scan available wifi provider*/
		else if (wifiManager.isWifiEnabled() == false) {
			wifiManager.setWifiEnabled(true);
			setWifi.setText("ON");
			listViwProvider.setVisibility(ListView.VISIBLE);
			scaning();
		}
	}

	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiverWifi);
	}

	protected void onResume() {
		registerReceiver(receiverWifi, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		super.onResume();
	}

	class WifiReceiver extends BroadcastReceiver {

		// This method call when number of wifi connections changed
		public void onReceive(Context c, Intent intent) {
			wifiList = wifiManager.getScanResults();
			
			/* sorting of wifi provider based on level */
			Collections.sort(wifiList, new Comparator<scanresult>() {
				@Override
				public int compare(ScanResult lhs, ScanResult rhs) {
					return (lhs.level > rhs.level ? -1
							: (lhs.level == rhs.level ? 0 : 1));
				}
			});
			listOfProvider.clear();
			String providerName;
			for (int i = 0; i < wifiList.size(); i++) {
				/* to get SSID and BSSID of wifi provider*/
				providerName = (wifiList.get(i).SSID).toString()
						+"\n"+(wifiList.get(i).BSSID).toString();
				listOfProvider.add(providerName);
			}
			/*setting list of all wifi provider in a List*/
			adapter = new ListAdapter(MainActivity.this, listOfProvider);
			listViwProvider.setAdapter(adapter);
			
			adapter.notifyDataSetChanged();
		}
	}
}

Java File : ListAdapter.java
ListAdapter.java file in package com.mobilemerit.adapter.
ListAdapter class set every available wifi providers list in a listView.

package com.mobilemerit.adapter;

import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.mobilemerit.wifi.R;

public class ListAdapter extends ArrayAdapter<string> {
	Activity mActivity;
	List</string><string> wifiName;
	private LayoutInflater inflater;

	public ListAdapter(Activity a, List</string><string> wifiName) {
		super(a, R.layout.single_list, wifiName);
		mActivity = a;
		inflater = LayoutInflater.from(mActivity);
		this.wifiName = wifiName;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = inflater.inflate(R.layout.single_list, parent, false);
		TextView wifiProvider = (TextView) convertView
				.findViewById(R.id.txt_wifi_provider);
		wifiProvider.setText(wifiName.get(position));
		return convertView;
	}

}
</string>

Java File : ImportDialog.java
importDialog.java file in package com.mobilemerit.javafiles.
ImportDialog class gives a dialog with full detail of wifi provider.

package com.mobilemerit.javafiles;

import android.app.Activity;
import android.app.AlertDialog;

public class ImportDialog {
	final CharSequence[] items = { "Take Photo From Gallery",
			"Take Photo From Camera" };
	Activity activity;
	AlertDialog dialog;
	AlertDialog.Builder builder;
	String detailProvader;

	public ImportDialog(Activity a, String detailProvader) {
		this.activity = a;
		this.detailProvader = detailProvader;
		builder = new AlertDialog.Builder(a);
	}

	public void showDialog() {

		builder.setTitle("wifi Provider Details");
		builder.setMessage(detailProvader);

		AlertDialog alert = builder.create();
		alert.show();
	}
}

Mainifest.xml
This is the main configuration file for wifi android project. This xml code will load required permission and main layout by default.

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

    <uses -sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19"></uses>

    <uses -permission android:name="android.permission.ACCESS_WIFI_STATE"></uses>
    <uses -permission android:name="android.permission.CHANGE_WIFI_STATE"></uses>

    <application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.mobilemerit.wifi.MainActivity"
            android:label="@string/app_name" >
            <intent -filter>
                <action android:name="android.intent.action.MAIN"></action>

                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent>
        </activity>
    </application>

</manifest>
Android App for detecting WiFi Signal
Android App for detecting WiFi Signal
Android App for detecting WiFi Signal

Download APK Download Source Code Contact Us

Android App for detecting Bluetooth Devices (with Source Code)

Android App for detecting Bluetooth Devices (with Source Code)

Download APK Download Source Code Contact Us

The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.

About Android App:

Android operating system is the fast growing mobile operating system in the market. Android provides solution for users to develop their own apps and upload to app store and help users to download for free of cost.

Layout Code: activity_main. Xml
When application is executed this is the first layout design that will run which will load width, height, load back ground details..etc.

<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=".MainActivity">

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Text"
        android:textAppearance="?android:attr/textAppearanceLarge"></textview>

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <Button android:id="@+id/turnOn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/on"></Button>

        <Button android:id="@+id/visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/visible"></Button>
    </LinearLayout>

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:orientation="vertical">

        <Button android:id="@+id/paired"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/List"></Button>

        <Button android:id="@+id/search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Find"></Button>

        <ListView android:id="@+id/listView1"
            android:layout_width="fill_parent"
            android:layout_height="200dp">
        </ListView>
    </LinearLayout>

</RelativeLayout>

Layout Code: string. Xml
this xml file inside values folder under RES. It’s contains all text resources.

< ?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Bluetoothtwo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="on">Turn On</string>
    <string name="List">List paired Devices</string>
    <string name="Find">Search new Devices</string>
    <string name="Text">Status: -</string>
    <string name="visible">Visible</string>
</resources>

Java File : MainActivity.java
MainActivity.java file in package com.mobilemerit.wifi.
Main activity file will load design form like buttons, text view, on click functionality, display text.

package com.mobilemerit.bluetooth;

import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mobilemerit.bluetooth.R;

public class MainActivity extends Activity implements OnClickListener {
	private static final int REQUEST_ENABLE_BT = 1;
	private Button onOffBtn;
	private Button listBtn;
	private Button findBtn;
	private Button visibleBtn;
	private TextView text;
	private BluetoothAdapter myBluetoothAdapter;
	private Set<bluetoothdevice> pairedDevices;
	private ListView myListView;
	private ArrayAdapter<string> BTArrayAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// take an instance of BluetoothAdapter - Bluetooth radio
		myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (myBluetoothAdapter == null) {
			onOffBtn.setEnabled(false);
			listBtn.setEnabled(false);
			findBtn.setEnabled(false);
			visibleBtn.setEnabled(false);
			text.setText("Status: not supported");
			Toast.makeText(getApplicationContext(),
					"Your device does not support Bluetooth", Toast.LENGTH_LONG)
					.show();
		} else {
			text = (TextView) findViewById(R.id.text);
			onOffBtn = (Button) findViewById(R.id.turnOn);
			onOffBtn.setOnClickListener(this);
			visibleBtn = (Button) findViewById(R.id.visible);
			visibleBtn.setOnClickListener(this);
			listBtn = (Button) findViewById(R.id.paired);
			listBtn.setOnClickListener(this);
			findBtn = (Button) findViewById(R.id.search);
			findBtn.setOnClickListener(this);
			myListView = (ListView) findViewById(R.id.listView1);

			// create the arrayAdapter that contains the BTDevices, and set it
			// to the ListView
			BTArrayAdapter = new ArrayAdapter</string><string>(this,
					android.R.layout.simple_list_item_1);
			myListView.setAdapter(BTArrayAdapter);
			/*
			 * checking while app start bluetooth is On or Off if bluetooth is
			 * on then search devices and set button and status "ON" if
			 * bluetooth is off then set button and status "OFF"
			 */
			if (!myBluetoothAdapter.isEnabled()) {
				onOffBtn.setText("Turn OFF");
				text.setText("Status: Disabled");
			} else {
				onOffBtn.setText("Turn ON");
				text.setText("Status: Enabled");
				find();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.turnOn:
			bluetoothOnOff();
			break;
		case R.id.visible:
			visible();
			break;
		case R.id.paired:
			list();
			break;
		case R.id.search:
			find();
			break;
		default:
			break;
		}
	}

	/* to enable and disable bluetooth */
	public void bluetoothOnOff() {
		if (!myBluetoothAdapter.isEnabled()) {
			Intent turnOnIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

		} else {
			myBluetoothAdapter.disable();
			onOffBtn.setText("Turn OFF");
			BTArrayAdapter.clear();
			Toast.makeText(getApplicationContext(), "Bluetooth turned off",
					Toast.LENGTH_SHORT).show();
		}
	}

	/* to make visible your device to other devices */
	public void visible() {
		Intent getVisible = new Intent(
				BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		startActivityForResult(getVisible, 0);
	}

	/* to search pair devices */
	public void list() {
		if (!myBluetoothAdapter.isEnabled()) {
			Toast.makeText(getApplicationContext(), "First Trun On Bluetooth",
					Toast.LENGTH_SHORT).show();
		} else {
			// get paired devices
			pairedDevices = myBluetoothAdapter.getBondedDevices();
			// put it's one to the adapter
			BTArrayAdapter.clear();
			for (BluetoothDevice device : pairedDevices)
				BTArrayAdapter.add(device.getName() + "\n"
						+ device.getAddress());
			Toast.makeText(getApplicationContext(), "Show Paired Devices",
					Toast.LENGTH_SHORT).show();
		}
	}

	/* to find all available devices */
	public void find() {
		if (!myBluetoothAdapter.isEnabled()) {
			Toast.makeText(getApplicationContext(), "First Trun On Bluetooth",
					Toast.LENGTH_SHORT).show();
		} else {
			BTArrayAdapter.clear();
			myBluetoothAdapter.startDiscovery();
			registerReceiver(bReceiver, new IntentFilter(
					BluetoothDevice.ACTION_FOUND));
		}
	}

	final BroadcastReceiver bReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// When discovery finds a device
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// Get the BluetoothDevice object from the Intent
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// add the name and the MAC address of the object to the
				// arrayAdapter
				BTArrayAdapter.add(device.getName() + "\n"
						+ device.getAddress());
				BTArrayAdapter.notifyDataSetChanged();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_ENABLE_BT) {
			if (myBluetoothAdapter.isEnabled()) {
				text.setText("Status: Enabled");
				onOffBtn.setText("Turn ON");
				Toast.makeText(getApplicationContext(), "Bluetooth turned on",
						Toast.LENGTH_SHORT).show();
				find();
			} else {
				text.setText("Status: Disabled");
				onOffBtn.setText("Turn OFF");
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(bReceiver);
	}
}

Mainifest.xml
This is the main configuration file for Bluetooth android project. This xml code will load required permission and main layout by default.

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

    <uses -sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19"></uses>
	<uses -permission android:name="android.permission.BLUETOOTH"></uses>
    <uses -permission android:name="android.permission.BLUETOOTH_ADMIN"></uses>
    <application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.mobilemerit.bluetooth.MainActivity"
            android:label="@string/app_name" 
            android:screenOrientation="portrait">
            <intent -filter>
                <action android:name="android.intent.action.MAIN"></action>

                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent>
        </activity>
    </application>

</manifest>
Android App for detecting Bluetooth Devices
Android App for detecting Bluetooth Devices
Android App for detecting Bluetooth Devices
Android App for detecting Bluetooth Devices

Download APK Download Source Code Contact Us

Accelerometer Android App (with Source code)

Accelerometer Android App (with Source code)

Download APK Download Source Code Contact Us

Using gestures often feels more natural than interacting with a user interface through mouse and keyboard. This is especially true for touch devices, such as smartphones and tablets. I find that using gestures can bring an Android application to life, making it more interesting and exciting for the user.

In this tutorial, we’ll use a accelerometer that you find in almost all android mobile device. We’ll use the accelerometer to identify the horizontal and vertical applied acceleration. And show the reading on x,y and z axis.

An acceleration sensor measures the acceleration applied to the device, including the force of gravity. The following code shows you how to get an instance of the default acceleration sensor:

private SensorManager mSensorManager;
private Sensor mAccelerometer;
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
You can access the sensor via the sensorManager.getDefaultSensor() method, which takes the sensor type and the delay defined as constants on SensorManager as parameters.
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}
protected void onResume() {
    super.onResume();
    senSensorManager.registerListener(this, mAccelerometer, mSensorManager.SENSOR_DELAY_NORMAL);
}

To avoid the unnecessary usage of battery power, you can register your listener in the onResume() method and de-register it in the onPause() method.

In order to receive notifications from the SensorManager when sensor values have changed.You have to implement SensorEventListener. Which has two public methods.

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

We can now start to focus on the meat of the application. It will require a bit of math to figure out direction of acceleration takes place. Most of the logic will go into theonSensorChanged method. We start by declaring a few variables in our class. Take a look at the code snippet below.

private float mLastX, mLastY, mLastZ;
private boolean mInitialized;
private final float THRESHOLD = (float) 2.0;

To get the values of each axis, we ask the sensor event for its values as shown below. The event’s values attribute is an array of floats.

float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

To keep the record of the initialisation of the accelerometer.We first hold the value of the previous x,y and then keep a flag to check whether its first time or not.

private boolean mInitialized;
@Override
	public void onSensorChanged(SensorEvent event) {
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		if (!mInitialized) {
			mLastX = x;
			mLastY = y;
			mLastZ = z;			
			mInitialized = true;
		} else {
			float deltaX = Math.abs(mLastX - x);
			float deltaY = Math.abs(mLastY - y);
			float deltaZ = Math.abs(mLastZ - z);
			if (deltaX < THRESHOLD) deltaX = (float)0.0;
			if (deltaY < THRESHOLD) deltaY = (float)0.0;
			if (deltaZ < THRESHOLD) deltaZ = (float)0.0;
			mLastX = x;
			mLastY = y;
			mLastZ = z;
			iv.setVisibility(View.VISIBLE);
			if (deltaX > deltaY) {
				//Horizaontal acceleration
			} else if (deltaY > deltaX) {
				//vertical acceleration
			} else {
				//No acceleration	
			}
		}

Download APK Download Source Code Contact Us