Showing posts with label Android Sensor. Show all posts
Showing posts with label Android Sensor. Show all posts

Saturday, 3 December 2016

Seonsor List in android example

How to get all Sensor List that available in android device.


In my last blogs, i had already taught you How  to get Sensor list in android device, but in this post i shows you this work by doing practical.

Saturday, 21 December 2013

Android-Light-sensor-example

Light Sensor

Like other sensor Light Sensor is also and hardware sensor that sense light.
Today i am going to create an Tourch Application that sense light and on/off flash light.

Source code for javafile



package in.androidshivendra.tourchapplication;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
//import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
//import android.view.View;
//import android.widget.ImageButton;

public class MainActivity extends Activity implements SensorEventListener {

SensorManager smgr;
Sensor msensor;

    private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    Parameters params;

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

        //code for sensor
     
        smgr = (SensorManager)getSystemService(SENSOR_SERVICE);
        msensor = smgr.getDefaultSensor(Sensor.TYPE_LIGHT);
     
     
     
     
 

   
        // First check if device is supporting flashlight or not      
        hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        if (!hasFlash) {
            // device doesn't support flash
            // Show alert message and close the application
            AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
                    .create();
            alert.setTitle("Error");
            alert.setMessage("Sorry, your device doesn't support flash light!");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // closing the application
                    finish();
                }
            });
            alert.show();
            return;
        }

        // get the camera
        getCamera();
       
   
    }

   
    // Get the camera
    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {
                Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
            }
        }
    }

   
     // Turning On flash
    private void turnOnFlash() {
        if (!isFlashOn) {
            if (camera == null || params == null) {
                return;
            }

           
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;


        }

    }


    // Turning Off flash
    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }
     
           
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;
           
         
        }
    }
   

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

    @Override
    protected void onPause() {
        super.onPause();
       
        // on pause turn off the flash
        smgr.unregisterListener(this);


    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
       
        // on resume turn on the flash
        smgr.registerListener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL);
 
    }

    @Override
    protected void onStart() {
        super.onStart();
       
        // on starting the app get the camera params
        getCamera();
    }

    @Override
    protected void onStop() {
        super.onStop();
       
        // on stop release the camera
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }


@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.values[0]<5 .0="" p=""> {


                 // turn on flash
                 turnOnFlash();
         
}
else
{
turnOffFlash();
}
}

}


Required Permission

uses-feature android:name="android.hardware.camera"
uses-permission android:name="android.permission.CAMERA"







Note:

This application only test on Real Device.


Saturday, 16 November 2013

Android Sensor Example

                                    Android Sensor Example

Welcome Friend,
            In this example i going to show a list of Sensor on a ListView that are available in device.In last Sensor post i told you how we create sensor base example.

And also explain Proximity sensor :- Proximity sensor sense the object minimum 0 to approx 2.5 cm.
so if any object come nearer to 2.5 cm from sensor it can generate some event.

Code for layout xml file: 

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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" >

   
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Scan Sensor" />

   
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

   
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="216dp" >

   

   
        android:id="@+id/imageSwitcher1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom" >

   


package in.androidshivendra.androidsensorexample;

import java.util.List;



import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener ,ViewFactory{

Button bscan;
ListView lv;
SensorManager smgr;
List msensor;

ImageSwitcher iv;
Sensor ses;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.activity_main);
bscan = (Button)findViewById(R.id.button1);
lv = (ListView)findViewById(R.id.listView1);
smgr = (SensorManager)getSystemService(SENSOR_SERVICE);
msensor=smgr.getSensorList(Sensor.TYPE_ALL);
iv = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
iv.setFactory(this);
final ArrayAdapter asens = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,msensor);
bscan.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
lv.setAdapter(asens);
}});
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView parent, View v, int pos,
long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, msensor.get(pos).getName(), Toast.LENGTH_SHORT).show();
}
});
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Sensor example", e.toString());
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@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.values[0] == 0){
iv.setImageResource(R.drawable.near);
}else{
iv.setImageResource(R.drawable.far);
}
}
protected void onResume() {
super.onResume();
ses = smgr.getDefaultSensor(Sensor.TYPE_PROXIMITY);
smgr.registerListener(this, ses, SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
super.onPause();
smgr.unregisterListener(this);
}

@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return iv;
}

}


Note: This application only Test on Real Device.You can download Application here


Monday, 28 October 2013

Android-GPS-Listener-Example

          Android-GPS-Listener-Example             

In Android, The location of Device (Phone)  we can get by Two way.
1. Using Network Provider
2. Using GPS.
Network Provider depend upon your SIM, while GPS depend upon Gps Hardware device.
Now I am going to explain how to create an application that show your device position.

Simple Android Example:

Create an Android Application project named LocationExample.                         


step1: Code for layout xml file: 


    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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" >

   
        android:id="@+id/textView1"
        android:layout_width="266dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        
        android:text="My Position"
        android:textAppearance="?android:attr/textAppearanceLarge" />

   

step 2 : code for Activity source java file.

package com.example.locationexample;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
TextView txt1;
LocationManager locationManager ;
LocationListener locationListener;
private Button btn1,btn2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
       
        txt1 = (TextView)findViewById(R.id.textView1);
        btn1 = (Button)findViewById(R.id.button1);
        btn2 = (Button)findViewById(R.id.button2);
        
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
       locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
              
              txt1.setText(String.valueOf(location.getLatitude())+","+String.valueOf(location.getLongitude()));
         Toast.makeText(MainActivity.this,"New Location detected"
        ,Toast.LENGTH_SHORT).show();
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
           
           
            }

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {
            Toast.makeText(MainActivity.this,"GPS/Use Wireless network is not enabled" ,Toast.LENGTH_SHORT).show();
           
           
            }
          };

        // Register the listener with the Location Manager to receive location updates
          
          btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
});
        
          btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
});

    }



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Step 3: you have to add Three permission   in manifest file by this way..
1.  android.permission.ACCESS_COARSE_LOCATION




2. android.permission.ACCESS_FINE_LOCATION 
3. android.permission.INTERNET  permission


uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
    uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
    uses-permission android:name="android.permission.INTERNET"
step4: Now your application is ready for run. Just Test it.

Open DDMS tool by this way:-
Windows-> Show Views -> other->Android->ShowView->Emulator Control.




Open an Android Google API Emulator.
Now Test your Application.






Saturday, 12 October 2013

Android Sensors example

Sensor

A sensor is a device, which responds to an input quantity by generating a functionally related output usually in the form of an electrical or optical signal.

In android several type of Sensor present like
  1. Proximity sensor
  2. Accelerator sensor
  3. Gyroscope sensor
  4. Location sensor
To create Sensor Based Application: We have to follow three step.

  1. Create instance of SensorManager
  2. Create instance of Sensor
  3. implement Sensor Event listener

SensorManager

Sensor Manager is use to get device sensor accessibility.

SensorManager mysensormanager = (SensorManager)getSystemService(SENSOR_SERVICE)


Sensor: 

it is a class that hold a particular sensor object.

Sensor mysensor = mysensormanager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

implement SensorEventListener: 

Now we have to override onAccuracyChanged(Sensor sensor, int accurracy) and onSensorChanged(SensorEvent event) method. what ever we want using sensor we have to write within onSensorChanged() method.


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

     public void onSensorChanged(SensorEvent event) {

     }

Note : Since Sensor is highly responsive so to make power efficient application we have to register and unregister SensorListerner smartly.
               we are normally register sensor event listener in on Resume() menthod  by calling registerListener().
protected void onResume() {
         super.onResume();
         mysensormanager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
     }
 and unregister in onPause method by calling unregisterListener(this);

     protected void onPause() {
         super.onPause();
         mSensorManager.unregisterListener(this);
     } 
Android-Sensor-Manager
Android Senor manager work flow


Today's Pageviews