Using Proximity sensor in Android

Hello everyone!

The term proximity is basically the fact, condition or position of being near or close by in space. A proximity sensor is a device capable of detecting presence of nearby objects without any physical contact. Some of the Android phones in the market today come equipped with a proximity sensor.

Through this post, we will learn how to use a proximity sensor in Android. As mentioned in the developer’s guide, the Android platform provides a sensor that lets you determine how close the face of a device is to an object (known as the proximity sensor).

Begin by creating a new Activity called ProximityTestActivity in any of your existing Android projects and add the following code!

ProximityTestActivity.java


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

public class ProximityTestActivity extends Activity {
	/** Called when the activity is first created. */

	private TextView txtProximitySensor, txtMaxProximity, txtReadingProximity;
	private SensorManager mSensorManager;
	private Sensor mProximitySensor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_proximity);
		
		txtProximitySensor = (TextView)findViewById(R.id.txtProximitySensor);
		txtMaxProximity = (TextView)findViewById(R.id.txtProximityMax);
		txtReadingProximity = (TextView)findViewById(R.id.txtProximityReading);

		mSensorManager = (SensorManager)getSystemService(
				Context.SENSOR_SERVICE);
		mProximitySensor = mSensorManager.getDefaultSensor(
				Sensor.TYPE_PROXIMITY);

		if (mProximitySensor == null){
			txtProximitySensor.setText("Proximity sensor is not present!"); 
		
		}else{
			txtProximitySensor.setText("Sensor present with name:" + " " +mProximitySensor.getName());
			txtMaxProximity.setText("Maximum Range: "
					+ String.valueOf(mProximitySensor.getMaximumRange()));
			mSensorManager.registerListener(proximitySensorEventListener,
					mProximitySensor,
					SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	SensorEventListener proximitySensorEventListener
	= new SensorEventListener(){
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			// TODO Auto-generated method stub
			if(event.sensor.getType()==Sensor.TYPE_PROXIMITY)
			{
				txtReadingProximity.setText("Proximity Sensor Reading:"
						+ String.valueOf(event.values[0]));
			}
		}
	};
}

activity_proximity.xml

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

    <TextView
        android:id="@+id/txtProximitySensor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/txtProximityMax"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtProximitySensor"/>

    <TextView
        android:id="@+id/txtProximityReading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtProximityMax"/>

</RelativeLayout>

Save all changes. Make sure no errors are present. Run the application on an Android device and you should see the following output!

output_1

output_2

Reference: Position sensors

What’s seen through [Glass]

Hey everyone!

Google Glass has been creating waves in the ocean of technology even since it’s inception at Google I/O 2012. The device has it’s own pros and cons and after having used it for over a month now, here’s a glimpse of what you see through;

[Glass]

Developing applications for Google Glass is pretty straightforward. Both the Mirror API and the GDK enable developers to create web based and native applications respectively for the wearable device. In addition, one can also try out various features that include winking to take photos, head angle detection, real time search and language translate options.

Recently, the second generation Google Glass device was launched in the United Kingdom that works with prescription glasses and has a detachable ear piece to improve voice-activated commands. To know more check out this space later…

Display static Google Maps in Android

Hi friends!

The Google Static Map web service enables developers to dynamically create a map image based on URL parameters (i.e. latitude, longitude, zoom level etc) sent through a standard HTTP request. When called it returns the map as an image allowing developers to display it on the user interface.

As mentioned on the developer’s page, the Google Static Maps API lets you embed a Google Maps image on your web page without requiring JavaScript or any dynamic page loading. The Google Static Map service creates your map based on URL parameters sent through a standard HTTP request and returns the map as an image that you can display on your web page.

Through this post, we will learn how to display a static Google map in Android.

Pre-requisites: Eclipse IDE, Android SDK

Create a new Activity class called TestStaticMapActivity in any of your existing Android projects and add the following code!

package com.app.test;

import java.io.IOException;
import java.io.InputStream;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

public class TestStaticMapActivity extends Activity {
	
	private ImageView iv;
	
	@Override
	public void onCreate(Bundle s){
		super.onCreate(s);
		setContentView(R.layout.activity_main);
		iv = (ImageView)findViewById(R.id.img1);
		new SendTask().execute();
		
	}
	
	private class SendTask extends AsyncTask<Bitmap, String, Bitmap>{

		@Override
		protected void onPostExecute(Bitmap bmp){
			iv.setImageBitmap(bmp);
		}

		@Override
		protected Bitmap doInBackground(Bitmap... params) {
			// TODO Auto-generated method stub
			Bitmap bm = getGoogleMapThumbnail(18.9750,72.8258);
			return bm;

		}	
		
	};

	public static Bitmap getGoogleMapThumbnail(double latitude, double longitude){
		
		String URL = "http://maps.google.com/maps/api/staticmap?center=" +latitude + "," + longitude + "&zoom=15&size=600x600&sensor=false";
		
		Bitmap bmp = null;
		HttpClient httpclient = new DefaultHttpClient();   
		HttpGet request = new HttpGet(URL); 

		InputStream in = null;
		try {
			in = httpclient.execute(request).getEntity().getContent();
			bmp = BitmapFactory.decodeStream(in);
			in.close();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bmp;
	}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
     
    <ImageView
        android:id="@+id/img1"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="fill_parent">
    </ImageView>

</RelativeLayout>

Do not forget to add the android.permission.INTERNET permission in your AndroidManifest.xml file.

Save all changes. Make sure no errors are present. Run the application on an Android device and you should see the following output!

output