Friday 30 January 2015

Android Sensor Example

Sensors can be used to monitor the three-dimensional device movement or change in the environment of the device.
Types Of Sensors
Android supports three types of sensors:

Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
Motion sensors that are supported on the Android platform.
1.TYPE_ACCELEROMETER
2.TYPE_GRAVITY
3.TYPE_GYROSCOPE
4.TYPE_GYROSCOPE_UNCALIBRATED
5.TYPE_LINEAR_ACCELERATION
6.TYPE_ROTATION_VECTOR
7.TYPE_SIGNIFICANT_MOTION
8.TYPE_STEP_COUNTER
9.TYPE_STEP_DETECTOR

 Position Sensors
These are used to measure the physical position of device.
Position sensors that are supported on the Android platform.
1.TYPE_GAME_ROTATION_VECTOR
2.TYPE_GEOMAGNETIC_ROTATION_VECTOR
3.TYPE_MAGNETIC_FIELD
4.TYPE_MAGNETIC_FIELD_UNCALIBRATED
5.TYPE_ORIENTATION
6.TYPE_PROXIMITY

Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
Environment sensors that are supported on the Android platform.
1.TYPE_AMBIENT_TEMPERATURE
2.TYPE_LIGHT
3.TYPE_PRESSURE
4.TYPE_TEMPERATURE
5.TYPE_RELATIVE_HUMIDITY

Android Sensor
Example:

MainActivity.java

import java.util.List;
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  implements SensorEventListener{
private SensorManager sensorManager;
private boolean isColor = false;  
private View view;  
 private long lastUpdate;  
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView sensorsData = (TextView)findViewById(R.id.textView1);
view = findViewById(R.id.textView2);  
view.setBackgroundColor(Color.GREEN);  
sensorManager = (SensorManager)this.getSystemService(SENSOR_SERVICE);
 /*SENSOR LIST*/
 List<Sensor> list = sensorManager.getSensorList(Sensor.TYPE_ALL);
 StringBuilder data = new StringBuilder();
data.append("Types Of Sensors:\n\n");
 for(Sensor sensor:list){
 data.append(sensor.getName() + "\n\n");
// data.append(sensor.getVendor() + "\n");
 // data.append(sensor.getVersion() + "\n");            
 }
 sensorsData.setText(data);
 /*Shaking Sensor*/
  lastUpdate = System.currentTimeMillis();  
}

//overriding two methods of SensorEventListener  
 @Override  
 public void onAccuracyChanged(Sensor sensor, int accuracy) {}  
 @Override  
public void onSensorChanged(SensorEvent event) {  
 if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {  
getAccelerometer(event);  
      }  
    }  
private void getAccelerometer(SensorEvent event) {  
 float[] values = event.values;  
  // Movement  
      float x = values[0];  
      float y = values[1];  
      float z = values[2];  
      float accelationSquareRoot = (x * x + y * y + z * z)  
          / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);  
      
      long actualTime = System.currentTimeMillis();  
      Toast.makeText(getApplicationContext(),String.valueOf(accelationSquareRoot)+" "+  
                  SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).show();  
        
      if (accelationSquareRoot >= 2) //it will be executed if you shuffle  
      {  
          
        if (actualTime - lastUpdate < 200) {  
          return;  
        }  
        lastUpdate = actualTime;//updating lastUpdate for next shuffle  
         if (isColor) {  
          view.setBackgroundColor(Color.GREEN);  

        } else {  
          view.setBackgroundColor(Color.RED);  
        }  
        isColor = !isColor;  
      }  
    }  

    @Override  
    protected void onResume() {  
      super.onResume();  
      // register this class as a listener for the orientation and  
      // accelerometer sensors  
      sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACC     ELEROMETER),  
    SensorManager.SENSOR_DELAY_NORMAL);  
    }  

    @Override  
    protected void onPause() {  
      // unregister listener  
      super.onPause();  
      sensorManager.unregisterListener(this);  
    }  

}

activity_main.xml:

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

   <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true" >

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

 <TextView
     android:id="@+id/textView2"
     android:layout_width="wrap_content"
     android:layout_height="57dp"
     android:text="Shake to switch color"
     android:textAppearance="?android:attr/textAppearanceLarge" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:textColor="#29166f"
      android:textAppearance="?android:attr/textAppearanceMedium" />

      </LinearLayout>
   </ScrollView>

</RelativeLayout>

Output:

Thursday 22 January 2015

Block Inbox SMS in Android With BroadcastReceiver

Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents

Creating the Broadcast Receiver:
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter.

public class IncomingSms extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) 
     {

       Toast toast = Toast.makeText(context, "Broadcast Receiver", duration);
toast.show();
      }
}

Registering Broadcast Receiver:

An application listens for specific broadcast intents by registering a broadcast receiver inAndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.

<receiver android:name="com.example.smsbroadcastreceiver.IncomingSms">   
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

Example:

IncomingSms.Java:

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + senderNum+ "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ",\n message: " + message, duration);
toast.show();
notification(context, message, senderNum);

}
}

} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);

}
}

public void notification(Context context, String Msg, String to) {
String message = Msg + "\n" + to;
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher).setTicker(message)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setContentText(message).setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationmanager.notify(0, builder.build());
}

}

MainActivity.java:

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

}

activity_main.Xml:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="When new SMS will come it will show a alert message." />

</RelativeLayout>

AndroidManifest.Xml:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
 <uses-permission android:name="android.permission.READ_SMS" />
<uses-permissionandroid:name="android.permission.SEND_SMS"/>

  <receiver android:name="com.example.smsbroadcastreceiver.IncomingSms">   
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
  </receiver>

Monday 12 January 2015

To Enable/Disable WiFi and Bluetooth Programmatically and Checking its Status

The following Sample Code describes To Enable/Disable WiFi and Bluetooth Programmatically and Checking its Status  in android:

1. activity_main.xml:
<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"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:text="MediumText"
            android:textColor="#ff0000"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MediumText"
            android:textColor="#29166f"
            android:textAppearance="?android:attr/textAppearanceMedium" />
        <CheckBox
            android:id="@+id/checkBox1"
            android:paddingLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
     <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/textView3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:textColor="#ff0000"
            android:text="MediumText"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MediumText"
            android:textColor="#29166f"
            android:textAppearance="?android:attr/textAppearanceMedium" />
        <CheckBox
            android:id="@+id/checkBox2"
            android:paddingLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>


2. MainActivity:

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
WifiManager wifi;
private BluetoothAdapter mBluetoothAdapter;
private TextView Bluetooth_text;
private TextView Bluetooth_status;
private CheckBox Bluetooth_check;
private TextView Wifi_text;
private CheckBox Wifi_check;
private TextView Wifi_status;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Wifi_text = (TextView) findViewById(R.id.textView1);
Wifi_status = (TextView) findViewById(R.id.textView2);
Wifi_check = (CheckBox) findViewById(R.id.checkBox1);
Bluetooth_text = (TextView) findViewById(R.id.textView3);
Bluetooth_status = (TextView) findViewById(R.id.textView4);
Bluetooth_check = (CheckBox) findViewById(R.id.checkBox2);
// Initiate wifi service manager
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Check for wifi is disabled
if (wifi.isWifiEnabled() == false) {
Wifi_text.setText("To Enable Wifi, Tick Your Checkbox");
Wifi_status.setText("Wifi Disabled");
Wifi_check.setChecked(false);
else {
Wifi_text.setText("To Disable Wifi, Untick Your Checkbox");
Wifi_status.setText("Wifi Enabled");
Wifi_check.setChecked(true);
}
// reference to the bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Bluetooth_text.setText("BlueTooth adapter not found");
Bluetooth_status.setText("BlueTooth Disabled");
Bluetooth_check.setChecked(false);
} else if (mBluetoothAdapter.isEnabled()) 
{
Bluetooth_text.setText("To Disable BlueTooth, Untick Your Checkbox");
Bluetooth_status.setText("BlueTooth Enabled");
Bluetooth_check.setChecked(true);
else {
Bluetooth_text.setText("To Enable BlueTooth, Tick Your Checkbox");
Bluetooth_status.setText("BlueTooth Disabled");
Bluetooth_check.setChecked(false);
}
Bluetooth_check.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
Bluetooth_text.setText("To Enable BlueTooth, Tick Your Checkbox");
Bluetooth_status.setText("BlueTooth Disabled");
Bluetooth_check.setChecked(false);
} else
 {
mBluetoothAdapter.enable();
Bluetooth_text.setText("To Disable BlueTooth, Untick Your Checkbox");
Bluetooth_status.setText("BlueTooth Enabled");
Bluetooth_check.setChecked(true);
}
}
});
Wifi_check.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (wifi.isWifiEnabled()) {
wifi.setWifiEnabled(false);
Wifi_text.setText("To Enable Wifi, Tick Your Checkbox");
Wifi_status.setText("Wifi Disabled");
Wifi_check.setChecked(false);
else {
wifi.setWifiEnabled(true);
Wifi_text.setText("To Disable Wifi, Untick Your Checkbox");
Wifi_status.setText("Wifi Enabled");
Wifi_check.setChecked(true);
}
}
});
}
}

3. Update ManifestFile:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
<uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> 
<uses-permission android:name="android.permission.BLUETOOTH" />
 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
ScreenShot:


Friday 9 January 2015

Android Checking Front & Back Camera and Take a photo automatically without user interaction

The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications. This document discusses a quick, simple approach to image and video capture and outlines an advanced approach for creating custom camera experiences for your users.

Code:

1. MainActivity.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.SurfaceView;
import android.widget.TextView;

public class MainActivity extends Activity{
private Camera camera; // camera object
private TextView TimeLeft; // time left field
File mediaFile;
private static final String IMAGE_DIRECTORY_NAME = "Captured_Images";
int numberOfCameras;
private TextView cameras;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimeLeft=(TextView)findViewById(R.id.TimeLeft); // make time left object
camera = Camera.open();
 numberOfCameras = Camera.getNumberOfCameras();
cameras=(TextView)findViewById(R.id.camera);
 if(numberOfCameras==0)
cameras.setText("Camera Not Supported in this Mobile");
else if(numberOfCameras==2)
 cameras.setText("No Of Cameras:"+numberOfCameras+"\n Both Front & Back Camera Available");
else
cameras.setText("No Of Cameras:"+numberOfCameras+"\n Back Camera only Available");
SurfaceView view = new SurfaceView(this);
try {
camera.setPreviewDisplay(view.getHolder()); // feed dummy surface to surface
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new CountDownTimer(10000,1000){
@Override
public void onFinish() {
// count finished
TimeLeft.setText("Picture Taken");
camera.takePicture(null, null, null, jpegCallBack);
}
 @Override
public void onTick(long millisUntilFinished) {
// every time 1 second passes
TimeLeft.setText("Seconds Left: "+millisUntilFinished/1000);
}
 }.start();
camera.startPreview();   
}
 Camera.PictureCallback jpegCallBack=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
  if (!mediaStorageDir.exists()) {
 if (!mediaStorageDir.mkdirs()) {
             }
}
 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".png");
try {
Bitmap userImage = BitmapFactory.decodeByteArray(data, 0, data.length);
// set file out stream
FileOutputStream out = new FileOutputStream(mediaFile);
// set compress format quality and stream
userImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}

2. Update Android Manifest File:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

3. activity_main.xml:

<?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"
    android:gravity="center">
    <TextView
android:id="@+id/camera"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#7ba400"/>

<TextView
android:id="@+id/TimeLeft"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="#29166f"
android:textAppearance="?android:attr/textAppearanceMedium"/>

</LinearLayout>

Output:
Photo has been taken automatically and stored in  Captured_Images folder in SD Card.

Tuesday 6 January 2015

Play Video on YouTube API With Custom Controls

The YouTube Data API (v3) lets you incorporate YouTube functionality into your own application. You can use the API to fetch search results and to retrieve, insert, update, and delete resources like videos or playlists.
In conjunction with the YouTube Player APIs and the YouTube Analytics API, the API lets your application provide a full-fledged YouTube experience that includes search and discovery, content creation, video playback, account management, and viewer statistics.
Create Project With YouTube API:
  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the YouTube Data API v3.
  4. In the sidebar on the left, select Credentials.
  5. The API supports two types of credentials. Create whichever credentials are appropriate for your project:
    • OAuth 2.0: Your application must send an OAuth 2.0 token with any request that accesses private user data. Your application sends a client ID and, possibly, a client secret to obtain a token. You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.
Download Project: From Here

Output:





Saturday 3 January 2015

Android - Draw route map between two geopoints

Download Google Play Services:
               Open EclipseWindowsAndroid SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.

Importing Google Play Services into Eclipse:

            1. In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace
2. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from.
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
3. Importantly while importing check Copy projects into workspace option (By default UnChecked).

Getting Google Map API Key:
          1. In eclipse goto WindowPreferencesExpand Android optionBuildcopy SHA1 fingerprint.
2. Now open Google API Console
3. Select Services on left side and turn on Google Maps Android API v2 & its Related APIs
4. Now select API Access on left side and on the right side click on Create new Android key
5. It will popup a window asking the SHA1 and package name. Enter your SHA1 and your android project package name separated by semicolon ; and click on create
6. Now new API key created.

Creating Project In Eclipse:


                        1. Download the app from here  Click Here


2. Import the Project into Eclipse by going to FileImportExpand AndroidSelect Existing Android code Into workspaceClick Next⇒Select Projectcheck Copy projects into workspace option (By default UnChecked)Click Finish.
3 Now we need to use Google Play Services project as a library to use project. So right click on project and select properties. In the properties window on left side select Android. On the right you can see Add button under library section. Click it and select google play services . Now Google Play Services added to our project. 
4. In this Project I have done t he following changes:

              i.   Add Permission to manifest file
              ii.  Put map key in manifest file
              iii. Updating Java and Xml File



OutPut: