Wednesday 27 March 2013

Sensors

A sensor (also called detector) is a converter that measures a physical quantity and converts
it into a signal which can be read by an observer or by an (today mostly electronic) instrument.

Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions.

The Android sensor framework lets you access many types of sensors. Some of these sensors are hardware-based and some are software-based. Hardware-based sensors are physical components built into a handset or tablet device.

The Android platform supports three broad categories of sensors:
1.Motion Sensors
2.Environmental Senosors
3.Position Sensors

1.Motion Sensors:
These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.


2.Environmental Sensors:
These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.


3.Position Sensors:
These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.

Sensors Android supports several sensors via the SensorManager .

for example have look on following example using SensorManager we can get the list of available sensors from android device.

Getting list of available Sensors:
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" >

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </ScrollView>

</RelativeLayout>

MainActivity.java:
package com.ram.sensor1;

import java.util.List;

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

public class MainActivity extends Activity {
SensorManager sensorManager;
TextView display;

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

display = (TextView) findViewById(R.id.textView1);

sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

List<Sensor> deviceSensors = sensorManager
.getSensorList(Sensor.TYPE_ALL);

StringBuffer sb = new StringBuffer();
sb.append("avialable sensors are :" + "\n" + deviceSensors.size()
+ " sensors found :" + "\n");

for (Sensor sensor : deviceSensors) {
sb.append(sensor.getName() + "\n" + "\n");
}

display.setText(sb);

}

}















Friday 22 March 2013

Custom ListView with ImageView

Hi to all, Here i'm posting example on Custom ListView with ImageView.
This app is done by my Student Harish.

In this project some images were used those images you can download from internet and store them in drawable folder in your application.

ScreenShots:

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        
        android:orientation="vertical" >

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

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="25dp"
        android:src="@drawable/ic_launcher"
        android:layout_gravity="top|left"
         />
    
</RelativeLayout>

</LinearLayout>

MainActivity.java:

package com.example.customlistview;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.listView1);
customadapter ca = new customadapter();
list.setAdapter(ca);

}

class customadapter extends BaseAdapter {

@Override
public int getCount() {
// TODO Auto-generated method stub
return images.length;
}

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub

return null;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(final int position, View convertview, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inflater = getLayoutInflater();
convertview = inflater.inflate(R.layout.custom, null);
TextView tv = (TextView) convertview.findViewById(R.id.textView1);
TextView tv1 = (TextView) convertview.findViewById(R.id.textView2);
ImageView image = (ImageView) convertview
.findViewById(R.id.imageView1);
tv.setText(names[position]);
tv1.setText(locations[position]);
image.setImageResource(images[position]);

return convertview;
}

}

String[] names = { "name1", "name2", "name3", "name4", "name5" };
String[] locations = { "location1", "location2", "location3", "location4",
"location5" };
int[] images = { R.drawable.a_aa, R.drawable.ee_r, R.drawable.sm_a,
R.drawable.sma_ll, R.drawable.ww_w };
}







Thursday 21 March 2013

BlueTooth Turn On and Off

 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.


Bluetooth Permission:
In order to use Bluetooth features in your application, you need to declare at least one of two
Bluetooth permissions: BLUETOOTH and BLUETOOTH_ADMIN.

You must request the BLUETOOTH permission in order to perform any Bluetooth communication, such
as requesting a connection, accepting a connection, and transferring data.

You must request the BLUETOOTH_ADMIN permission in order to initiate device discovery or
manipulate Bluetooth settings. Most applications need this permission solely for the ability to
discover local Bluetooth devices. The other abilities granted by this permission should not be
used, unless the application is a "power manager" that will modify Bluetooth settings upon user
request. Note: If you use BLUETOOTH_ADMIN permission, then must also have the BLUETOOTH
permission.


<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

Setting Up Bluetooth:
Before your application can communicate over Bluetooth, you need to verify that Bluetooth is supported on the device, and if so, ensure that it is enabled.

If Bluetooth is not supported, then you should gracefully disable any Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the user enable Bluetooth without leaving your application. This setup is accomplished in two steps, using the BluetoothAdapter.




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

     <CheckBox
        android:id="@+id/cboxEnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable"
        android:textSize="20dp"/>

</RelativeLayout>


MainActivity.java:
package com.ram.bt;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    BluetoothAdapter bluetoothAdapter;
    Integer REQ_BT_ENABLE = 1;
    CheckBox enable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
       
        enable = (CheckBox) findViewById(R.id.enableCheckBox);
       
        enable.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if (buttonView.isChecked()) {
                    if (bluetoothAdapter == null) {
                        Toast.makeText(getApplicationContext(),
                                "Device doesn't support Bluetooth",
                                Toast.LENGTH_LONG).show();
                    } else {
                        if (!bluetoothAdapter.isEnabled()) {   
                            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//implicit intent
                           
                            startActivityForResult(enableBtIntent,REQ_BT_ENABLE);
                           
                            Toast.makeText(getApplicationContext(),"Enabling Bluetooth....", Toast.LENGTH_LONG).show();
                        }
                    }
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Disabling Bluetooth....", Toast.LENGTH_LONG).show();
                    bluetoothAdapter.disable();
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == REQ_BT_ENABLE) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(getApplicationContext(),
                        "BlueTooth is now Enabled..", Toast.LENGTH_LONG).show();
            }
            if (resultCode == RESULT_CANCELED) {
                Toast.makeText(
                        getApplicationContext(),
                        "Error occured while enabling BlueTooth....",
                        Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}



Wednesday 13 March 2013

Downloading Image in Android

ScreenShots:

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="72dp"
        android:layout_marginTop="74dp"
          />

</RelativeLayout>

MainActivity.java:
package com.ram.downloadimage1;

import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private String imageURL = "http://www.fnordware.com/superpng/pnggrad8rgb.png";
    private ImageView image;

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

        image = (ImageView) findViewById(R.id.imageView1);

        ImgDownload img = new ImgDownload();

        img.execute();

    }

    private class ImgDownload extends AsyncTask {
        ProgressDialog pd;
        private Bitmap pic;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            pd = ProgressDialog.show(MainActivity.this, "downloading Image",
                    "Plz wait");

            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {

                // This class can be manipulate URLs of any protocol
                URL url = new URL(imageURL);

                // URLConnection must be configured before it has connected to
                // the remote resource. Instances of URLConnection are not
                // reusable: you must use a different instance for each
                // connection to a resource

                URLConnection conn = url.openConnection();

                // Decode an input stream into a bitmap. If the input stream is
                // null, or cannot be used to decode a bitmap, the function
                // returns null. The stream's position will be where ever it was
                // after the encoded data was read.

                pic = BitmapFactory.decodeStream(conn.getInputStream());
            } catch (Exception ex) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            pd.cancel();
            image.setImageBitmap(pic);
        }
    }
}

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.downloadimage1.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>
    </application>

</manifest>

 

Disabling and Enabling Button

Here a simple method is available to enable and disable button that is

To Disable:
         setEnabled(false);
and

To Enable:
         setEnabled(true);

Example:
ScreenShot:

Before disabling button:
After disabling button:



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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="43dp"
        android:text="Display Message"
        android:textSize="20sp" />

</RelativeLayout>


MainActivity.java:
package com.ram.disablingbutton;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

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

final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

               //Disabling button
b.setEnabled(false);

Toast.makeText(getApplicationContext(),
"Look at the button it is desabled..",
Toast.LENGTH_LONG).show();

}
});
}

}


What is Context ?

Interface to global information about an application environment. This is an abstract class whose implementation provided by the Android system . It allows access to application-specific resources and classes , as well as up-calls for application level  operations such as launching activities,broadcasting and receiving intents, etc 

Thursday 7 March 2013

Google Maps Android API v2

NOTE: Version 1 of the Google Maps Android API has been officially deprecated as of December 3rd, 2012 . This means that from March 3rd , 2013 you will no longer will able to request an API key for this  version. No new features will be added to Google Maps API v1 . However , apps using v1 will continue work on devices. Existing and new developers are encouraged to use Google Maps Android API v2.


NOTE: You cannot run your application using Google Play API(Google Maps Android API V2) on Android emulator, Because your emulator doesn't support Google Play services. So you need to check your application in Android mobile phone which supports google play services.

watch video tutorial here:click here

download this project here :GoogleMapsAndroidAPIV2 


Here i'm giving the procedure how to setup Google Map Android API v2 SDK and integrating in Application.

ScreenShot:


Step1: Download and configure the Google Play Services SDK. In Eclipse open go to window menu
          and run Android SDK Manager and under Extras select Google Play Services package and
         download it.

Step 2: Now create your application where you want use Google maps api v2.

Step 3: Import Google Play Services library project in eclipse

  • Under package explorer right click choose import option and under android choose importing existing project into workspace as  follows.


  • In next window choose browse option and open your ADT Bundle has been located or your Android SDK and inside open extras folder and open google folder and open google_play _service folder and choose libproject folder and click ok button.



  • After clicking ok button under Import Project window select google play service lib project and click finish button.


  • After clicking finish button you will observe in under package explorer google_play_services_lib project has been added.


Step4: Adding googleplay_services_lib to our project:
  • Right click on project and choose properties option and select android .
  • Under library choose add option and add googleplay_service_library to our project as follows:

Next


Next again perform same action.
  • Right click on project and choose properties option and select android and if you got following error under library then follow the bellow procedure.

Note: you will get this problem because of lengthy path.

open adt bundle -->open sdk folder-->open extras folder-->open google folder-->open googleplayservices folder-->copy lib project and paste in your current workspace folder and from there import libproject after importing add library to the project now you wont get any error.


Step5: Finding SHA1 fingerprint key

Now two ways are avialable to findout SHA1 key 
Procedure1:
  • Go to window menu choose preferences under preferences choose android under that choose build and copy SHA1 fingerprint key as follows:
    


or

Procedure 2:
  • If your using windows operation system follow below procedure
  1. Under package explorer right click and choose properties.
  2. Under Android choose build and there you can see default debug keystore copy that keystore value.
  3. After goto MyComputer and open the drive where your operating system has been located and under that drive open program files folder there you will see java folder open that and open jre folder on bin folder click SHIFT+Right click choose open command window here and type following command.
  4. keytool -list --alias androiddebugkey -keystore "paste your default debug keystore here" -storepass android -keypass android
  5. After executing above command you will get SHA1 certificate fingerpint key copy that and go to internet and in Google type google api console and there sign in using your google account.
  • If your using Mac or Linux operating system procedure is very easy just type following command in Terminal
  • keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

After executing above command you will get SHA1 certificate fingerpint key copy that and go to internet and in Google type google api console and there sign in using your google account.

Step 5: Sign in google api console website as follows

Next


Step 6: After signing in follow the steps below

  • -->Under google api's console select create project option as follows

Next
-->provide project name and select create button.


Next
-->After selecting create button you will get following window.
-->In following window from left side navigation bar select APIs & auth option as follows


Next
-->In following window scroll down and activate Google Maps Android API v2 Services by clicking on OFF button to ON

Next


Next
-->Select Credentials option from left side navigation bar under APIs option


Next
-->After selecting Credentials option next you will get following window 
-->From following window select CREATE NEW KEY option

  • In following window enter your SHA1 cerficate fingerprint key (go to step5)with semicolon and after enter your application package name as follows.
  • And click create button.

Next
-->After selecting create button you will get following window from following window you can copy the map API key and insert into AndroidManifest.xml.



Step 7: Go to eclipse open your application and open AndroidManifest.xml file and insert following code .

AndroidManifest.xml:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!--
     The following two permissions are not required to use
     Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <permission
        android:name="your application package name.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="your application package name.permission.MAPS_RECEIVE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.googlemapsv2.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>
<meta-data
            android:name="com.google.android.gms.version"

            android:value="@integer/google_play_services_version" />

         <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="paste your api key here" />
    </application>

</manifest> 

Step 8: Insert following code in your activity_main.xml

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment  
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"
          />
</LinearLayout>

Step 9: Insert following code in your MainActivity.java

MainActivity.java:
package com.ram.googlemapsv2;

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

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;

public class MainActivity extends Activity {
GoogleMap map;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// map.setMapType(GoogleMap.MAP_TYPE_NONE);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
}