Search This Blog

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

Sunday, 21 October 2012

call on a telephone number


This post is describing that how to make a call from the Android phone using Intent.ACTION_CALL.

Start a activity with as follows and pass your telephone number

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + <your tel number>));
activity.startActivity(callIntent);

To check the state of the phone call and actions setup a call listener as follows

private class EndCallListener extends PhoneStateListener { 
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if(TelephonyManager.CALL_STATE_RINGING == state) {
            Log.i("contactus", "RINGING, number: " + incomingNumber);
        }
        if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
            Log.i("contactus", "OFFHOOK");
        }
        if(TelephonyManager.CALL_STATE_IDLE == state) {
            if (incomingNumber.equals(szListentelNumber) == true) {
                 Intent i = activity.getBaseContext().getPackageManager()
                        .getLaunchIntentForPackage(
                                activity.getBaseContext().getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    activity.startActivity(i);
             }
            Log.i("contactus", "IDLE" + incomingNumber);
        }
    }
}
public void setUpCallListener(String szTelNumber) {
     this.szListentelNumber = szTelNumber;
     EndCallListener callListener = new EndCallListener();
     TelephonyManager mTM = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
     mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
    
}

Enjoy the coding with Android and if you like this simple post please provide your feedback.

Thanks
Creative Android Apps

Thursday, 2 August 2012

Twitter Live Streaming - Sample Code

Social media is the key ingredient of applications and integrating the social media platform with mobile applications the key of success for your mobile applications.


The large social networks could not fit to one single mobile application increasing the opportunity for all mobile developers to create more interesting and creative small apps for mobile devices with this social platforms.


Twitter is one of the popular social networking platform. The update on twitter is very fast as tweets are small in size. Twitter introduced the live streaming APIs to get the updates in real time from twitter live streaming service.


You can integrate the twitter live streaming in your android application as described in this post.


Create a default activity project in eclipse for android and create the following layout for your application in activity_main.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/StartTweetsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Start Tweets"
android:onClick="startTweets" />
<Button
android:id="@+id/StopTweetsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Stop Tweets"
android:onClick="stopTweets" />
<EditText
android:id="@+id/SearchText"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>
<ListView android:id="@+id/TweetsList"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
></ListView>
</LinearLayout>


Now replace the default activity class code by the following code

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;



public class MainActivity extends Activity implements View.OnClickListener {

    private List<HashMap<String,String>> mTweets = new ArrayList<HashMap<String,String>>();
    private SimpleAdapter mAdapter;
    private boolean m_Running = false;
    private String m_SearchKeyWord = "";
    final int MAXLIST = 10;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //create a list view and bind with simple adapter
        mAdapter = new SimpleAdapter(this, mTweets, android.R.layout.simple_list_item_2, new String[] {"Tweet", "From"}, new int[] {android.R.id.text1, android.R.id.text2});
        ListView lv = (ListView)findViewById(R.id.TweetsList);
        lv.setAdapter(mAdapter);
        //create a list view and bind with simple adapter
    }
   
    public class StreamTask extends AsyncTask<Context, Boolean, Boolean> {
        protected Boolean doInBackground(Context... arg0) {
            try
            {
            DefaultHttpClient client = new DefaultHttpClient();
            String userName = "XXXXXXX";
            String password = "XXXXXXX";
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(userName, password);
            client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
            HttpGet request = new HttpGet();
            String m_SearchKeyWord = null;
            request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + m_SearchKeyWord));
            HttpResponse response = client.execute(request);
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
            handleTweets(reader);
            
            in.close();
            }
            catch (Exception e) {
            Log.e("SampleTwitter", "doInBackground_" + e.toString());
            }
            return true;
        }
         private void handleTweets( BufferedReader reader ) {
                try {
                    String line = "";
                    
                    do
                    {
                        line = reader.readLine();
                        JSONObject tweet = new JSONObject(line);
                        HashMap<String, String> tweetMap = new HashMap<String, String>();
                        if (tweet.has("text")) {
                            Log.i("SampleTwitter","Tweet : " + tweet.getString("text"));
                            tweetMap.put("Tweet", tweet.getString("text"));
                            tweetMap.put("From", tweet.getJSONObject("user") .getString("screen_name"));
                            Log.i("SampleTwitter","From : " + tweet.getJSONObject("user") .getString("screen_name"));
                            mTweets.add(0, tweetMap);
                            if (mTweets.size() > MAXLIST) 
                            {
                                mTweets.remove(mTweets.size() - 1);
                            }
                            publishProgress(true);
                        }
                    } while (m_Running && line.length() > 0);
                }
                catch (Exception e) {
                    Log.e("SampleTwitter", "handleTweets_" + e.toString());
                }
            }
         
        
    
        protected void onProgressUpdate(Boolean... values) {
            super.onProgressUpdate(values);
            mAdapter.notifyDataSetChanged();
            Log.d("SampleTwitter", "Im in onProgressUpdate()");
        }
        
    }
    public void stopTweets(View view ) {
        m_Running = false;
        for(int idx=mTweets.size()-1;idx>=0;idx--)
            mTweets.remove(idx);
        if(mTweets.size() ==1)
            mTweets.remove(0);
        mAdapter.notifyDataSetChanged();
    }
   public void startTweets(View view) {
        
        if( m_Running == false ) 
        {
            EditText edt = (EditText)findViewById(R.id.SearchText);
            m_SearchKeyWord =  edt.getText().toString();
            if( m_SearchKeyWord.length() > 0 ) 
            {
                StreamTask st = new StreamTask();
                st.execute();
                m_Running = true;
                
            }
            else 
            {
                Toast.makeText(this, "Please enter the search keyword", Toast.LENGTH_SHORT).show();
            }
        }
        else 
        {
            Toast.makeText(this, "Already Running", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        
    }

    
}

This sample is getting the twitter updates from real time stream API and showing that in a list view. you need to change the username and password values in doInBackGround() method to connect to the twitter.


The following is URL on which we can send a https request to get the tweets update in real time based on the tag value or search keyword.


https://stream.twitter.com/1/statuses/filter.json?track=?


The AsyncTask is the best way to implement the tweets updates in background. The StreamTask in the sample is extending the AsyncTask and implementing the doInBackGround()  method to create a https connection with twitter service and receive a JSON response. The JSON response is parsed by the 
handleTweets() method. The method extract the text tweets and add in the hash map to update in the list view.


To update the UI in background function in AsyncTask the publishProgress will send the update to the onProgressUpdate method of AsyncTask. 


mAdapter.notifyDataSetChanged();


This call will send a signal to the list view adapter about the change of data and the UI thread update the list view.


See the output of the sample here


Twitter
Twitter Live Streaming




if you like the post then please provide your feedback.


Thanks
Creative Android Apps


Wednesday, 1 August 2012

Using Camera in Android Application


The picture speaks more then your words. The picture is the key ingredient for a application interacting with physical world.


Android provides the very easy interface with the existing camera application to quickly integrate the camera function to your application. You can take picture and easily access the image data in your application with very few line of code in android.


This post is explaining the quick integration of the existing camera application with your own android application.


To capture the photo from existing camera application you can use the following line of code.


private void dispatchTakePictureIntent(int actionCode) {
    Intent PictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(PictureIntent, actionCode);
}


To get the photo in your application you simple need to implement onActivityResult() method which. The image data bundled in the extras as a bitmap and return to the caller in onActivityResult method.


private void onActivityResult(Intent intent) {
    Bundle extras = intent.getExtras();
    Bitmap mImageBitmap = (Bitmap) extras.get("data");
    
}

Now you can play with this bitmap data in your application.


Thanks
Creative Android Apps

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


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




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

Saturday, 14 July 2012

Sample Code - Creating Option Menu in Android


Sample Code - Create a Option Menu for Android Application

The option menu is a core menu of  the application which provides the basic navigation for applications.

I have written this post the explain the use of option menu in android application.


The best way to create an option menu is to define the option menu in a XML file and inflate the menu resource in onCreateOptionMenu method.

Create a project and define an activity as CreativeMenus (you can use any other name for your activity).


Create the XML file in res->layout directory as menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action1"
          android:icon="@drawable/ic_launcher"
          android:title="@string/action1"
          />
    <item android:id="@+id/action2"
          android:icon="@drawable/ic_launcher"
          android:title="@string/action2" />
    <item android:id="@+id/action3"
          android:icon="@drawable/ic_launcher"
          android:title="@string/action3" />
    <item android:id="@+id/action4"
          android:icon="@drawable/ic_launcher"
          android:title="@string/action4" />
</menu>

Now implement the activity class as follows

package com.example.creativeapps;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class CreativeMenus extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);
        return true;
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
         switch (item.getItemId()) {
            case R.id.action1: //start another activity
                startActivity(new Intent(this, CreativelayoutsActivity.class));
                return true;
            case R.id.action2:
                //TODO: handle the code for action 2
                return true;
            case R.id.action3:
                //TODO: handle the code for action 3
                return true;
            case R.id.action4:
                //TODO: handle the code for action 4
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}


To handle the click events on action items you need to implement the onOptionsItemSelected method of your activity class. Get the unique id defined for each item to handle the proper action for click on menu item.


See in the above example we are starting the another activity on click of action1. you can extend the example by implementing your own actions.


Menus are good to implement for version lower then 3.0 for Android version 3.0 or greater implement the action bar.


Please provide your feedback and share this to your creative android friends.


Creative Android Apps




Basics about Menu in Android

Menus in Android 


Menu is the basic navigation method for an application which provides an interactive way to interact with user interface and defines the application actions for its users.


In Android version 2.3.X (API level 10) the Menu is the basic building block of the application invoked by the system when user press the menu button on device. In later versions from Android 3.0 on-wards this is replaced by an action bar on the top of device.


Android defines the three type of menus for applications

Option Menu

The option menu is the primary collection of action items for an application. If you are developing an application for android devices running the Android 2.3.X or lower version then option menu will be created by the system when ever user press the menu button on device. 


The Android 3.0 converts this into more effective method using the action bar.

Contextual Menu

A contextual menu is a floating menu invoked when user performs a long click on an element of the view.

Popup Menu

A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu.

You can define the menus in your android application as XML resources which could be inflate in your activity or fragment.

See here a sample file defining a menu for an application

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/myaction1"
          android:icon="@drawable/ic_myaction1"
          android:title="@string/myaction1"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" />
</menu>



Monday, 9 July 2012

Android 4.1 Jelly Bean - Whats New



Android 4.1 Jelly Bean User Experience



Android 4.1 Jelly Bean recently launch with great features for users.The most interesting and popular mobile operating system and application development platform presented with exciting features in Google I/O. The new features for android users has created a unique and interesting topic to talk. Today's post is all about the new and exciting features of Android 4.1 for all users who love the platform.

Faster , Faster & Faster 

The buttery and silky user interface is much more faster then previous version. The uniform and reactive responses enhanced the user touch experience and you can enjoy every touch of your finger.

Actions With Beauty

Expandable notifications added great actions and beautiful user interface provides a complete renovation of your old devices. The mix of actions and beauty creates a bold platform for users.



Personalized Your Phone

Android 4.1 redefines the user experiences by adding the new home widgets now you can personalized your home screen, the home screen will automatically make a room for your favorite apps when you put those on your home screen.

Create a new experience with Camera

Now swipe the camera to take filmstrip view and automatically select the best picture. Simply share your best moments with new camera enhancements.

Smarter Keyboard and Fast Voice Processing

The smart keyboard automatically predicts the next word for you before you start typing. More accurate dictionaries and a fast voice processing without moving your voice on cloud for processing.

Accessibility for every one

Jelly Bean added the accessibility for every one by adding the new gesture mode to reliably navigate the user interface by blind users in combination with speech output. Added support for accessibility plugins to enable external Braille input and output devices using USA and Bluetooth interfaces.

Share Your Moments with Android Beam

Now tap your phones to share without internet connections using android beam. You can use your phone to pay, share photos, videos and much more with all NFC devices using android beam.

Google Now 

Now get what you want at what time google will present automatically for you using the new google now services. It remembers where you walk and move and keep posting you the latest around that.

Now get you android Jelly Bean Phone and enjoy the new experiences. Google Nexus 7 is now available with Android 4.1 Jelly Bean.

Like the post the please provide your feedback and if i missed any thing new in jelly bean let me know.





Tuesday, 3 July 2012

Using the Contact Provider to Display the Contact List


Contact Provider Sample


Contact Provider provides the access to the contact database and allow the apps to add,delete,modify and query the contact database. This post is focusing on displaying the list of contacts to a list view.


Create a android project in eclipse and open the main.xml from the res->layout->main.xml.


Add a list view to the xml layout file

<ListView android:layout_width="match_parent"
              android:id="@+id/contactList"
              android:layout_height="wrap_content"
              android:layout_weight="1"/>

Add a new xml layout file named as contact_info.xml

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/GridLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:columnCount="2"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/contactEntryText"
        android:layout_gravity="fill_horizontal"
        android:text="@+id/contactEntryText" />
</GridLayout>


Now open the activity class and add the following code.

public class ContactSampleActivity extends Activity {
    /** Called when the activity is first created. */
    private ListView mContactList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mContactList = (ListView) findViewById(R.id.contactlist);
        showContactList();
    }
    
    private void showContactList() {
        // Build adapter with contact entries
        Cursor cursor = getContacts();
        String[] fields = new String[] {
                ContactsContract.Data.DISPLAY_NAME
        };
        @SuppressWarnings("deprecation")
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_info, cursor,
                fields, new int[] {R.id.contactEntryText});
        mContactList.setAdapter(adapter);
    }

    /**
     * Obtains the contact list for the currently selected account.
     *
     * @return A cursor for for accessing the contact list.
     */
    private Cursor getContacts()
    {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        
        String[] projection = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + "1" + "'";
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    }

}

By running this sample you will get the list of all the contacts with their display name. You need to test this on your phone to see the list.






Monday, 2 July 2012

Basics of Notifications in Andoird

Android provides the notification APIs for applications to push the notifications for the user on the device.

Toast Notification


The toast notifications invoke on the surface of the window.You can invoke the toast notifications from the Activity or Service.The Toast notifications acquire the area equivalent to the message and automatically fades. The user current activity is interactive upon the display of the toast notification.

The toast notification doesn't provide any interaction to the user. They are only useful to send the read only messages as notification to the user.

Create the simple toast notification in your activity class.

Context context = getApplicationContext();
CharSequence text = "Hi,I am a toast notification";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
 

Status Bar Notification

The status bar notification provides the interaction with the user. The notifications which need a response from the end user should add to the status bar notifications. A status notification add a icon to the system status bar and a notification message in the notification window.

When user selects the notification the android fires and Intent  to launch the Activity defined by notification.

The sound,vibration or flashing lights could also be used for notification.

The background services need to notify the event which needs user response in the status notification.

The status notifications are managed in android using Notification and NotificationManager classes. 

The Notification class defines the notification which includes the status icon, message and the action (Activity to start as response from user).

The Notification manager class manages the notification system service and handle all the status bar notifications in android.

To create a simple status notification you can follow the following steps

Get a instance of the Notification manager as follows

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =  
(NotificationManager) getSystemService(ns);

Now create a notification object as follows

int icon = R.drawable.notification_icon;
CharSequence tickerText = "StatusBar";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, LanuchAsResponse.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
 
Now notify the notification to the status bar as follows

private static final int SAMPLE_ID = 1;

mNotificationManager.notify(SAMPLE_ID, notification);