Search This Blog

Thursday 26 July 2012

Google Place APIs



Google Place APIs



Google Place API is a service which provides the search system for places. The search with the google place API can be perform by two ways.


1) Text String Search - a normal search specify the search string as text
2) User location based search - a search specified based on the location parameters (latitude,longitude)


You can integrate the places search based on the location in your android application. See the previous example to determine the location of a user and draw a overlay icon pointed to that location of the user.


This post is explaining the implementation of place search by google place API.


The HTTP URL for the place search is as follows

https://maps.googleapis.com/maps/api/place/search/output?parameters

The output could be json or xml and the required parameters are as follows


key - Your application key.
location - latitude,longitude of the place to search
radius - search area in which the search should perform for location
sensor - true or false based on the request is initiated by a devices having a location sensor (GPS) enabled or disabled


The following is the list of optional parameters to refine your search


Keyword — A term to be matched against all content that Google has indexed for the place
Language — The language code, indicating in which language the results should be returned.
Name — A term to be matched against the names of Places. Results will be restricted to those containing the values passed here.
Rankby — Specifies the order in which results are listed. Possible values are:

· Prominence - This option sorts results based on their importance.
· Distance - This option sorts results in ascending order by their distance from the specified location.
· Types — Restricts the results to places matching at least one of the specified types. Types must be separated with a pipe symbol (type1|type2|etc).
· Pagetoken — Returns the next 20 results from a previously run search.



   Code : The following few line of code explain how can you call google web    service in your application.

    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        result = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();

The Google Place APIs provide a quick way to integrate the context aware search to your application. 


If you like the post please provide your feedback. 


Thanks
Creative Android Apps






Tuesday 24 July 2012

Exception networkonmainthreadexception in Android


Exception networkonmainthreadexception in Android



This exception is due to the StrictMode introduced on honeycomb or later android devices to not allow the network operations in main thread.


The solution to this exception is that you implement a thread for network operation instead of implementing in main thread.


The alternative method is to disable the option which is enable by default in honeycomb and later android OS.The previous versions of android OS allowed the main thread to create the network connections.


Disabling the StrictMode in Android


StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);


If you like the solution please provide your comments.


Thanks
Creative Android Apps

Monday 23 July 2012

Integrating Facebook in Android Apps


Quick integration of facebook on android platform



Hello Creative Android Developers,


This post is explaining the integration of facebook a powerful social media with android applications.


facebook the powerful social media provides the enrich developer APIs to integrate the facebook features in applications. You can create lots of derivative social apps from facebook and can add a social touch to your app with facebook interaction.


This post is focusing on developing the android application with facebook APIs. The facebook SDK could be download from https://github.com/facebook/facebook-android-sdk/


Once you download the facebook-android-sdk you need to create an android project to compile the facebook-android-sdk code and create a library for facebook APIs.


Now you can create your sample code by using the above library as reference in your application.


Create a simple android application project and replace the activity code as follows.


You need to register your application on facebook platform and get the application id from the platform.

package com.example.samplefacebook;

import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import com.facebook.android.*;
import com.facebook.android.Facebook.*;

public class MainActivity extends Activity {

   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    
    Facebook facebook = new Facebook("YOUR APP ID");

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

        facebook.authorize(this, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {}

            @Override
            public void onFacebookError(FacebookError error) {}

            @Override
            public void onError(DialogError e) {}

            @Override
            public void onCancel() {}
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
    
}


This is the simple code for invoking the login interface with single-sign-on (SSO) of the facebook from your android application. 


You need to add the following permission to access the facebook platform.


Add the following line in AndroidManifest.xml of the sample.

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

Now running the application we show the following output

facebook on android
Facebook - (SSO) in Android App

Now you can make your apps more social with facebook. If you like the post then please provide your feedback.


Thanks
Creative Android Apps



Sunday 22 July 2012

Sample Code - Implementing the sensor in Android


Sample Code - TYPE_LIGHT sensor to get the screen brightness for android device



Android provide the android.hardware framework to implement the sensors. you could get a quick understanding of android sensor framework for our previous post.


http://creativeandroidapps.blogspot.in/2012/07/basics-of-sensors-on-android-platform.html


This post will explain the implementation of SensorEventListener for the TYPE_LIGHT sensor. The light listener is used to control the brightness of the screen.


You need to create a Android Application Project in your eclipse editor and modify the Activity class to extend with SensorEventListener.  See the following code of the sample.

package com.example.samplesensor;

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.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mLight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onSensorChanged(SensorEvent arg0) {
        // TODO Auto-generated method stub
        float lux = arg0.values[0];
        Toast.makeText(getApplicationContext(), "Sensor Value " + lux, 1000).show();
    }

    @Override
      protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
      }

      @Override
      protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
      }
}


Get the instance of the system service of sensor manager and get the TYPE_LIGHT sensor from the system.
You need to implement the two callback methods provided by the SessionEventListener.


The sensor need to register on the onResume() and onPause() methods of activity class.


The TYPE_LIGHT sensor only returns the one value which is brightness of the device screen. The brightness of the screen is measured by lux unit.


One lux is equal to one lumen per square metre.


If you like the example please provide your feedback.


Thanks
Creative Android Apps


Sensors framework for Android



Android Sensor Framework


Android provides a development framework to develop the applications with various sensors described in the following post.


http://creativeandroidapps.blogspot.in/2012/07/basics-of-sensors-on-android-platform.html

Android provides a android.hardware package which includes the following four classes for sensor management.

SensorManager - Sensor Manager is a class to manage the various sensors provides the methods to list the sensors available on the device, register the sensor listeners and acquire the sensors data. You can use this class to create an instance of the sensor service.


Sensor - This class provides the methods specific to a sensor. The sensor manager returns the sensor object which can use to handle the sensor functions which depends on the type of the sensor.


SensorEvent - The framework defines this class to handle the sensor events and create a object of sensor event. A sensor event object includes the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp for the event.


SensorEventListener - The sensor event listener provides the two callback methods to implement to receive the sensor events when sensor changes its value or when sensor accuracy changes.


Now you can see the next article to create quick sample for sensors on android platform.


http://creativeandroidapps.blogspot.in/2012/07/sample-code-implementing-sensor-in.html


If you like the post please provide your feedback.


Thanks
Creative Android Apps

Basics of Sensors on Android Platform



Basics about the sensors in Android



The sensors add a value to the Android device just like our sense organs add a value to our life. Android platform provide a rich set of sensors which could be use by applications in many ways. This post will describe about the various sensors and its use for applications on android platform.


Most of the sensors will measure the device motion , orientation and environmental changes. Android divide the sensors in two categories.


Hardware Sensors - The hardware sensors are the physical components embedded on the device and measure the environmental changes like acceleration, geomagnetic field strength, and device rotations.


Software Sensors - The software sensors are not embedded as physical components, they are basic derive the sensor values for hardware devices. The software sensors are also known as virtual sensors.
The gravity sensors are the example of software sensors.


According to the  usage the android provides the following types of sensors

  • Motion Sensors
  • Environmental Sensors
  • Position Sensors
Its not necessary that all devices have all type of sensors, most of the android devices have accelerometer and magnetometer. The device could also have multiple sensors of same type.

see the list of sensors for android platform with there usage.

Sensor
Type
Description
Common Uses
TYPE_ACCELEROMETER
Hardware
Measures the acceleration force in m/s2that is applied to a device on all three physical axes (x, y, and z), including the force of gravity.
Motion detection (shake, tilt, etc.).
TYPE_AMBIENT_TEMPERATURE
Hardware
Measures the ambient room temperature in degrees Celsius (°C). See note below.
Monitoring air temperatures.
TYPE_GRAVITY
Software or Hardware
Measures the force of gravity in m/s2that is applied to a device on all three physical axes (x, y, z).
Motion detection (shake, tilt, etc.).
TYPE_GYROSCOPE
Hardware
Measures a device's rate of rotation in rad/s around each of the three physical axes (x, y, and z).
Rotation detection (spin, turn, etc.).
TYPE_LIGHT
Hardware
Measures the ambient light level (illumination) in lx.
Controlling screen brightness.
TYPE_LINEAR_ACCELERATION
Software or Hardware
Measures the acceleration force in m/s2that is applied to a device on all three physical axes (x, y, and z), excluding the force of gravity.
Monitoring acceleration along a single axis.
TYPE_MAGNETIC_FIELD
Hardware
Measures the ambient geomagnetic field for all three physical axes (x, y, z) in μT.
Creating a compass.
TYPE_ORIENTATION
Software
Measures degrees of rotation that a device makes around all three physical axes (x, y, z).
Determining device position.
TYPE_PRESSURE
Hardware
Measures the ambient air pressure in hpa or mbar.
Monitoring air pressure changes.
TYPE_PROXIMITY
Hardware
Measures the proximity of an object in cm relative to the view screen of a device. This sensor is typically used to determine whether a handset is being held up to a person's ear.
Phone position during a call.
TYPE_RELATIVE_HUMIDITY
Hardware
Measures the relative ambient humidity in percent (%).
Monitoring dewpoint, absolute, and relative humidity.
TYPE_ROTATION_VECTOR
Software or Hardware
Measures the orientation of a device by providing the three elements of the device's rotation vector.
Motion detection and rotation detection.
TYPE_TEMPERATURE
Hardware
Measures the temperature of the device in degrees Celsius (°C).
Monitoring temperatures.

You can develop very interesting applications around sensors like motion sensor based games, weather applications, motion detection applications, checking your position and much more.

Android provides a complete development framework is android SDK to manage the sensors. Please read the following post to get more details on the android framework.

If you like the post please provide your feedback as comments.

Thanks
Creative Android Apps

Thursday 19 July 2012

Basics of Dialog Box in Android


Dialog Box in Android


Dialog Box is the best way to show the message popup in an application or on screen selection for user inputs. The Android provides the dialog interface which could be integrate with activity to get the user inputs as well as provide the responses to user.


Android defines the Dialog as class to create the dialog which can be display with in an activity. You should not use the Dialog class directly as the extended classes are also defined by Android which you can use directly in your application.


The four major type of Dialog classes are as follows


AlertDialog - is the most useful dialog class and most of the dialog interfaces could be design using the AlertDialog. You can define your controls to customize the Alert Dialog UI.

Android Alert Dialog
Android - AlertDialog


ProgressDialog - is used to show the progress as a progress bar or progress wheel. You can define your controls to customize the ProgressDialog also.

Android Progress Wheel
Android - Progress Wheel


Android Progress Bar
Android - Progress Bar


DatePickerDialog - is used to select a date by the user.


TimePickerDialog - is used to select a time by the user.

Android Date and Time Pickers
Android - Pickers (Date and Time)

If you like the post please provide your feedback.


Thanks
Creative Android Apps




Android Jelly Bean released to play on Open Source


Excitement Over - Google Released Jelly Bean Source Code in AOSP


After a lot of excitement for Jelly Bean (Android 4.1) Google recently released its version to the open source community to develop and release the future versions and releases.


Very soon we can see more and more devices running the Jelly Bean (Android 4.1). Currently Google released the native binaries for Nexus 7 tablet and Galaxy Nexus. Google's Jean Baptiste Queru recently announced the release of Android 4.1 on AOSP (Android Open Source Project). The name of the tagged release is android-4.1.1_r1 as JBQ stated in the Android Building Group. The name of the development branch is jb-dev. We recommended that you create new clients, even if you're working in the master branch.It'll make your clients smaller and faster to sync.


Now the developers can create there customized builds of Jelly Bean and create new applications with new android power of Jelly Bean. Jelly Bean is released with lots of exciting features and APIs for developers providing new means to sharing the applications and connecting the devices.


See more about the android 4.1 Jelly Bean Features here


http://creativeandroidapps.blogspot.in/2012/06/whats-new-in-jelly-belly-android-41.html


You can download the latest source code from https://android.googlesource.com/.

If you like the post please share to your friends and feedback us with your valuable comments.


Thanks
Creative Android Apps


Wednesday 18 July 2012

Restarting Innovation - Big Software Sliced into Small Apps


Restarting Software World By Slicing the Big Software into small apps



The software world is restarting the innovation by slicing the big software into small apps and serving to large community! real users.


Today's web world is changing the definition of the software from development to usage. The Big Software is now sliced into small apps and reaching to more real consumers. The complex technologies moved into black box and the simple technologies are in hand of end users.


The changes are already started in year 2008 when the mobile applications market started emerging. Now you can see the social apps and much more is very hot today.


The next future of the business will be Apps which redefine the business by giving better access to all the end users.You can see the changes that now the big accounting software's turned into personalized accounting apps, social activities are associated with technology using apps,banking software is sliced into small apps and distributed to its real end users.


This exciting change is happening due to advancement in web technologies, users awareness and device revolution to create a better interconnect world. The businesses are reducing there cost of operations, developers could get more opportunities and end users will have more access and confidence.


The smart phones, smart tablets and more smart embedded devices are increasing in the world and motivating the developers to create more beautiful world around the technologies.


The desktop apps, web apps, cloud apps, mobile apps, social apps and much more ways of apps are emerging to create a better life for every one.

The traditional and legacy software applications will be completely removed from the world and the new era of software will be start where the big technology will be served into small and creative apps to its real end users.


So are you ready to join the restart of software innovation. Push the button of apps and start new innovation.


If you like the post please share your comments.


Thanks
Creative Android Apps




Sample Code for Open GL in Android


Sample Code for Open GL in Android


Now your basic Open GL ES concepts are clear as written in the previous post (http://creativeandroidapps.blogspot.in/2012/07/basics-of-opengl-in-android.html) you are ready to create something with OpenGL on Android in your creative application.


This post is explaining a very popular sample for the Open GL for the new developers to quickly understand the implementation of Open GL functions and classes. For a basic Open GL project you need to create a activity class where you host your GLSurfaceView. The render something on the view we need to implement the GLSurfaceView.Renderer interface.


See here the code of my sample class.

Create a Activity Class

package com.example.sampleopengl;

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


public class MainActivity extends Activity {

    private MyGLSurfaceView mGLView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGLView = new MyGLSurfaceView(this,null);
        setContentView(mGLView);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    
}


See the highlighted code which you need to add in your activity class after implementing the following two classes.


Now create a class named MyGLSurfaceView which extends the GLSurfaceView to set as the view of activity.

package com.example.sampleopengl;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class MyGLSurfaceView extends GLSurfaceView {

    MyGLRenderer mRenderer;
    public MyGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        mRenderer = new MyGLRenderer();
        setRenderer(mRenderer);
    }
    //change the color on touch
    public boolean onTouchEvent(final MotionEvent event) {
        queueEvent(new Runnable(){
            public void run() {
                mRenderer.setColor(event.getX() / getWidth(),
                        event.getY() / getHeight(), 1.0f);
            }});
            return true;
        }

}



See the implementation of the Renderer which will render the color.


package com.example.sampleopengl;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;

public class MyGLRenderer implements GLSurfaceView.Renderer {
    private float mRed;
    private float mGreen;
    private float mBlue;
    
      public void setColor(float r, float g, float b) {
        mRed = r;
        mGreen = g;
        mBlue = b;
    }

    @Override  //function draw the opengl graphics
    public void onDrawFrame(GL10 gl) {
        // TODO Auto-generated method stub
         gl.glClearColor(mRed, mGreen, mBlue, 1.0f);
         gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int w, int h) {
        // TODO Auto-generated method stub
        gl.glViewport(0, 0, w, h);
        
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
        // TODO Auto-generated method stub
        
        
    }


}


Now you can run the sample code and see the following result as your first sample of Open GL on android.

Open GL Android
Open GL - Color 1

On touch you will see a color change on the Open GL surface view created in activity.

Open GL Android
Open GL - Color 2


If you like the post please provide your feedback.


Thanks
Creative Android Apps



Tuesday 17 July 2012

Basics of OpenGL in Android


Basics about OpenGL ES for Android


OpenGL is an open graphics library to create the high performance 2D and 3D applications.The OpenGL ES is a specification for the embedded devices. The devices comes with GPU (graphics processing unit) accelerate the OpenGL functions and draw the high quality graphics on the screen.


There is lot of stuff on OpenGL which is not useful to start quickly with OpenGL ES on Android. This post is giving a quick start-up for developers to easily understand the basic about the OpenGL ES concepts around the Android application development.


OpenGL is a cross platform library and supports on multiple platforms.


Android support the OpenGL interface programming using the application development in java as well as the native (NDK) support.


The Android SDK has a android.opengl package to create the OpenGL graphics in android applications.


The android.opengl is a static interface and implements the OpenGL ES 1.0/1.1 specifications to create a high performance graphics in 2D and 3D.


The two main classes which need to implement in an OpenGL based application on android platform are as follows.


GLSurfaceView - GLSurfaceView provides a View class to implement with OpenGL 2D and 3D APIs just like the normal SurfaceView in Android. You can extend the GLSurfaceView class to create your own class and use that View to create for your activity.


All the events you want to handle on this view need to implement in the class you extended with GLSurfaceView.


GLSurfaceView.Renderer - This is an interface which provides the class to draw the OpenGL objects in GLSurfaceView. You should implement a separate class for Renderer and use that class to associate with GLSurfaceView instance by using the setRenderer method.


Now you can start trying with OpenGL samples for Android.


See the first sample here


http://creativeandroidapps.blogspot.in/2012/07/sample-code-for-open-gl-in-android.html


If you like this article then please provide your valuable comments.


Thanks
Creative Android Apps







Monday 16 July 2012

Sample Code - Add a Image on Google Map

Add a Image on Google Map using Overlay

Integration of Google Map with location applications provides a better navigation for user. You can add custom images , text and view on the Map View using the Overlay class provided by Google APIs.

See the previous post to integrate the location listener with your basic google map view.


This post will focus on adding a image on the map view on the detected location by the location listener.


You can use the Overlay class from com.google.android.maps package.

Now create a new class "GLocate.java" in your sample application which is extending the com.google.android.maps.Overlay class.


See the code as follows

package com.example.gmapsample;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class GLocate extends com.google.android.maps.Overlay{

    GeoPoint location = null;
    Bitmap overlay_img = null;
    public GLocate(GeoPoint location)
    {
        super();
        this.location = location;
    }
    
    public void setImage(Bitmap bmp)
    {
        this.overlay_img = bmp;
    }
    
    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow)
     {
         super.draw(canvas, mapView, shadow);
         //translate the screen pixels
         Paint p = new Paint();
         Point screenPoint = new Point();
         mapView.getProjection().toPixels(this.location, screenPoint);
         Log.i("GLocate","draw : x = "+ screenPoint.x + "y= " + screenPoint.y);
         //add the image
         canvas.drawBitmap(overlay_img,screenPoint.x, screenPoint.y , p); //Setting the image  location on the screen (x,y).
         mapView.invalidate(); //redraw the map view
     }

 }


Now integrate the class in your main activity code as follows (see the highlighted lines of code)


 @Override
        public void onLocationChanged(Location location) {
        // A new location update is received.  Do something useful with it. 
            Log.i(TAG,"Location Listener start");
            String coordinates[] = {""+location.getLatitude(), ""+location.getLongitude()};
            double lat = Double.parseDouble(coordinates[0]);
            double lng = Double.parseDouble(coordinates[1]);
            GeoPoint p = new GeoPoint((int) (lat * 1E6),(int) (lng * 1E6));
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.caalogo);
            GLocate gl = new GLocate(p);
            gl.setImage(bmp);
            List listOfOverLays = mapView.getOverlays();
            listOfOverLays.clear();
            listOfOverLays.add(gl);
            mapController.animateTo(p);
            mapController.setZoom(4);
            mapView.invalidate();     

        }



Now run the application and send the location update using the DDMS tool explained in previous post (http://creativeandroidapps.blogspot.in/2012/07/sample-code-update-google-map-using.html ).


The output of the application is as follows.


Google Map
Google Map - Overlay Image






Please provide your valuable feedback.


Thanks
Creative Android Apps









Sample Code - Update Google Map using Location listener

Sample Code - Update Google Map using Location listener

Implement the basic example of google map as explained in the following post.


This post will focus on implementing the location listener and update the location in google map.

You need to add the following code for the location listener in the class extending the MapActivity class (see the GMapSample class from the previous sample)

private final LocationListener listener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // A new location update is received.  Do something useful with it.  
             Log.i(TAG,"Location Listener start");
             String coordinates[] = {""+location.getLatitude(), ""+location.getLongitude()};
                double lat = Double.parseDouble(coordinates[0]);
                double lng = Double.parseDouble(coordinates[1]);
                GeoPoint p = new GeoPoint(
                (int) (lat * 1E6),
                (int) (lng * 1E6));
                mapController.animateTo(p);
                mapController.setZoom(7);
                mapView.invalidate();     

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.i(TAG,"Location disable");
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.i(TAG,"Location enabldes");
        }

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

Now add a location manager object in class as follows


private LocationManager locMgr;


Add the following lines of highlighted code in the onCreate Method to register the location listener with location manager.



@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gsample);
        mapView = (MapView) findViewById(R.id.map_view);      
        mapView.setBuiltInZoomControls(true);
        locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //register the location listener with location manager       
        locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
        GeoPoint point = new GeoPoint(latitudeE6, longitudeE6);

        mapController = mapView.getController();
        mapController.animateTo(point);
        mapController.setZoom(7);
        mapView.invalidate();     
                          
    }

The eclipse will not automatically add the import required for location APIs


import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;


Now when you run the application you can see the following output.








To send the location data to the emulator for testing you can use the DDMS tool


DDMS Tool Android
DDMS Tool

select the emulator device and go to the Emulator Control. See the Location Controls and update the location data and click send to send the location data to the emulator running the application.


If you like the post then please provide your feedback.


Thanks
Creative Android Apps

Sunday 15 July 2012

Get Application Key for Google Map

Get the apiKey for Google Map



Google Map integration in your android application requires a key to integrate with your application.


This post will explain the procedure to get the apiKey for your android application for Google and explain the integration of Google Map with your application.


To get the apiKey we need to follow the following steps

  • Locate the debug.keystore 
  • Locate the keytool.exe
  • Generate the MD5 fingerprint using keytool and debug.keystore
  • Get the API Key from Google by providing the MD5 fingerprint
You can find the debug.keystore file user directory of your operating system

For Example  : C:\Users\XXXX\.android\debug.keystore

You can find the keytool.exe in your %JAVA_HOME%\bin\keytool.exe

Now run the following command to get the MD5 fingerprint

C:\Program Files\Java\jdk1.6.0_01\bin>keytool.exe  -list -alias androiddebugkey
-keystore C:\Users\t\.android\debug.keystore -storepass android -keypass android

See the output of the command as following screen shot

MD5 fingerprint with Key Tool
Now register this MD5 fingerprint to get the Google Map API Key as follows

Go to the following link


Copy the MD5 fingerprint and click on Generate Key to get your application key.

Add the application key value to the MapView XML object as follows

 <com.google.android.maps.MapView
                 android:id="@+id/map_view"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:apiKey="0HvaRYYCBNDap4SKY0HN-XXXXXXXXXXXXXX"
                 />

Now you are ready to use the Google Map in your application see here how to integrate the basic google map object in your application.


http://creativeandroidapps.blogspot.in/2012/07/google-map-in-android-application.html




If you like the post then please provide your feedback.


Thanks
Creative Android Apps

Google Map in Android Application - Sample Code


Sample Code - Google Map in Android Application


Location aware applications on android platform needs an intuitive way to present the location information.
Google provides a set of APIs to integrate the Google Map for development of android applications and bundled as Google APIs.


This post is focusing on Google Map object integration with android application.


Create a Android application project "GMapSample" and open the default class file generated in the src directory as the main activity class. See here the project creation dialog


Eclipse Android Project
Create New Android Application Project Using Eclipse
To create the Google Map in the application you need to select the Build SDK as Google APIs (API15). If this is not available then you need to update the SDK and download using Android SDK Manager.


The following includes need to add in order to integrate the Google Map with your application.


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;


The MapActivity extends the basic Activity class of Android and provides the Google Map as the user interface.


In order to access the Google Map in your application you need to get a Application Key and define the Google Map object in your application XML layout.


 <com.google.android.maps.MapView
                 android:id="@+id/map_view"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:apiKey="0HvaRYYCBNDap4SKY0HN-XXXXXXXXXXXXXXXX"
                 />


To get the API key for your application see the following link.


http://creativeandroidapps.blogspot.in/2012/07/get-application-key-for-google-map.html


Now replace the code of main activity class by following code


package com.example.gmapsample;

import android.os.Bundle;

import android.view.Menu;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;


public class GMapSample extends MapActivity{

    private static final String TAG = "GMapSample";
    private MapView mapView;
    private MapController mapController;
    private static final int latitudeE6 = 17421306;
    private static final int longitudeE6 = 78457553;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gsample);
        mapView = (MapView) findViewById(R.id.map_view);   //get the map view resource added in XML file   
        mapView.setBuiltInZoomControls(true);
        GeoPoint point = new GeoPoint(latitudeE6, longitudeE6); //defines the geo location
        mapController = mapView.getController(); //get the map controller
        mapController.animateTo(point); // show the location defined by geopoint
        mapController.setZoom(7);  //setting the map zoom level
        mapView.invalidate();  //redraw the map   
                          
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_gsample, menu);
        return true;
    }
    
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}


while compiling the application you will get some error because we have not added the use of google APIs in AndroidManifest.xml file of the application.


Add the following line in your application manifest file.


<uses-library android:name="com.google.android.maps" />


Add the following permissions also to manifest file.



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




To run the application you need to define a AVD from the AVD Manager as follows


AVD Manager
AVD for Google Map


Running the application will give the following output.


Google Map Android
Android Application with Google Map
Please provide your feedback. The next post for the Google Map is on the way.


Thanks
Creative Android Apps