Thursday, June 16, 2011

Get Current Location in Android / Obtaining User Location

In Android Three Approaches are preferred to Get Current Location -> Using GPS -> Cell - Id -> Wi-Fi The above three gives a clue to get the current location. Gps gives the results accurately. But it consumes Battery. Android Network Location Provider get the current location based wifi signals and cell tower. We have to use both  or a single to Get the Current Location
LocationManager myManager;
MyLocListener loc;
loc = new MyLocListener();
myManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc );
package com.gps.activities;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public class MyLocListener implements LocationListener
{
    //Here you will get the latitude and longitude of a current location.
    @Override
    public void onLocationChanged(Location location)
    {
            if(location != null)
            {
                     Log.e("Latitude :", ""+location.getLatitude());
                     Log.e("Latitude :", ""+location.getLongitude());
            }
    }
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
       
    }
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
       
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
       
    }
}
Note: 
 Include the below permissions in manifast.xml to listen Location Updates.

<uses-permission       android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission     android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Note : If you want more details about Obtaining User Location/ Get User Location refer the below link. http://developer.android.com/guide/topics/location/obtaining-user-location.html

Tuesday, June 14, 2011

Shared Preferences Persistent Storage in Android

In android we have more ways to store persistent data. Shared Preferences is one of the way to store primitive private data.
    Shared Preferences store data in the form of key value pairs. Using shared preferences we can store string, booleans, float, int, long etc.
    Shared Preferences store data until app uninstallation. 

Example:
 //Reading values from the Preferences
SharedPreferences prefs = getSharedPreferences("Pref_Name", MODE_WORLD_READABLE);
int StoredDealNumber =  prefs.getInt("Key", 0);

In order modify data in preferences we have to use Editor.
//Modification of the Preferences
SharedPreferences prefs = getSharedPreferences("Pref_Name", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor     Prefeditor = prefs.edit();
Prefeditor .putInt("no", 1); // value to store
Prefeditor .commit();

Note:
After modification we have commit the values. Otherwise the values are not modified.

Monday, June 13, 2011

Publising the android application to market place

Signing is the final step of the development of an application. In order to submit any application to the android market place you have to sign the application.Signing can be done in two ways. Manually and with the help of editor(eclipse). With the help of editor it is very easy to sign an application.
Using Eclipse:

-> Right click on the project
-> In the Menu select Android Tools
-> Select Export Signed Application package. The following menu appears.
   Date Slider is the name of the project. Click on Next.
    If you have any keystore then select existing keystore. Otherwise select the other option and fill the appropriate details. Click on the next.
Minimum validity is 10000 days but 25 years Recommended. Fill the other details. Click the Next.
Browse the destination file path And click on Finish.

Note :
-> Before signing the application check the manifast file for the android:debuggable if it exist then   remove the this tag.
-> Versioning the  application properly.
-> Test the application completely.

If You want complete information then refer the following link
http://developer.android.com/guide/publishing/app-signing.html

Friday, June 10, 2011

Handling Orientation Change in Android

If you want perform some operation in the orientation the following snippet useful. If you change the orientation then one default method will call i.e onConfigurationChanged()

@Override
 public void onConfigurationChanged(Configuration newConfig)
{
         super.onConfigurationChanged(newConfig);
         if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
         {           
                  // indicates orientation changed to landscape
         }             
         else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
         {           
                  // indicates orientation changed to portrait
         }            
}

Note :
We will change the declaration of the Activity in manifast.xml to the following :
<activity android:name=".YourActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden" />

If you want know more information about this plz follow the link :
http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange   

getting current screen orientation in android

The following snippet gives the current screen orientation.

public int getScreenOrientation()
{
        return getResources().getConfiguration().orientation;
}

The above method return integer. We will compare as follows.

 if(getScreenOrientation() == Configuration.ORIENTATION_PORTRAIT)
 {
            //App is in Portrait mode
 }
 else
{
           //App is in LandScape mode
}


Thursday, May 19, 2011

Android Expandable ListView

A view that shows items in a vertically scrolling two-level list. This differs from the ListView by allowing two levels: groups which can individually be expanded to show its children. The items come from the ExpandableListAdapter associated with this view.

Steps to develop Expandable List :
-> Initialize the Expandable List View
-> Construct the Expandable List Adapter
-> Set the Adapter to Expandable List View


Initialize the Expandable List View
 ExpandableListView explvList;
 explvList = (ExpandableListView)findViewById(R.id.explvList);
Construct the Expandable List Adapter 
    public class ExpLvAdapter extends BaseExpandableListAdapter
    {
        @Override
        public Object getChild(int groupPosition, int childPosition)
        {           
            return childPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition)
        {
           
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
        {
            TextView tv = null;
            tv = new TextView(Home.this);
            tv.setText("ChildView "+groupPosition);           
            tv.setPadding(30, 0, 0, 0);
            return tv;
        }
        @Override
        public int getChildrenCount(int groupPosition)
        {   
            return children[groupPosition].length;
        }

        @Override
        public Object getGroup(int groupPosition)
        {
            return groupPosition;
        }

        @Override
        public int getGroupCount()
        {
           
            return 2;
        }

        @Override
        public long getGroupId(int groupPosition)
        {
           
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent)
        {
            TextView tv = null;
            tv = new TextView(Home.this);
            tv.setText("GroupView "+groupPosition);           
            tv.setPadding(30, 0, 0, 0);
            return tv;
        }

        @Override
        public boolean hasStableIds()
        {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition)
        {
           
            return true;
        }
    }


Set the Adapter to Expandable List View
explvList.setAdapter(new ExpLvAdapter());
Output:

Wednesday, May 18, 2011

Starting an Android Service at Boot time

Always a service is started by us manually that means it was not start by default. If we switch off the mobile then all the running services will stop.

For example if we are running a service. If we reboot the mobile then all the running services are stopped. So we have to run the service again.

By default android broadcasts a intent (android.intent.action.BOOT_COMPLETED)at the time of booting. So we have to receive that and in that we again start a service.

This should be accomplished by using Broad Cast Receiver.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootBroadcastReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Log.i("Receiver Called.", "start the service.");
}
}
We have to add this receiver in the manifast.xml. The code is as follows.
<!-- Reciver -->
<receiver android:name=".BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>

Tuesday, May 17, 2011

Android Service

A Service is a Android Class used to run a process in background to avoid Application Not Responding errors.
Example:
Home.java:
package com.sercivedemo.activities;

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

public class Home extends Activity
{
    Button btnStartService, btnStopservice;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnStartService = (Button)findViewById(R.id.btnStartService);
        btnStopservice = (Button)findViewById(R.id.btnStopservice);
       
        btnStartService.setOnClickListener(new OnClickListener()
        {          
            @Override
            public void onClick(View arg0)
            {
                startService(new Intent(Home.this, ServiceEx.class));
            }
        });
       
        btnStopservice.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                stopService(new Intent(Home.this, ServiceEx.class));
            }
        });
    }
}

ServiceEx.java:
package com.sercivedemo.activities;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class ServiceEx extends Service
{   
    Timer objTimer;
    @Override
    public void onCreate()
    {       
        super.onCreate();
        Log.e("Service :", "onCreate()");
       
        //Do the process here
     }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.e("Service :", "onDestroy()");
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        Log.e("Service :", "onStart()");
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}
main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
    <Button
        android:layout_width="wrap_content"
        android:id="@+id/btnStartService"
        android:text="StartService"
        android:layout_height="wrap_content">
    </Button>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnStopservice"
        android:text="StopService">
    </Button>   
   
</LinearLayout>

Android Launching Camera and attach the image to image view


public void takePhoto()
{
        //Intent to launch camara
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
       
        //Uri creattion to strore images
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+ "/" +   String.valueOf(System.currentTimeMillis())+ ".jpg"));
                   
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

        startActivityForResult(intent, 1);

}


protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
       super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
      
       if(requestCode == 1)
       {
           if(resultCode == RESULT_OK)
           {
                try
               {
                   ivPhoto.setBackgroundResource(0);
                   ivPhoto.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(new File(mImageCaptureUri.getPath()))));
               }
               catch (FileNotFoundException e)
               {               
                   e.printStackTrace();
               }
           }
           else if(resultCode == RESULT_CANCELED)
           {
               Log.d("Result: ", "Launch Cancelled.");
           }
     }
}

Call takePhoto() in the button click. 

Note: 

In the manifast.xml we have to add permissions.android.permission.WRITE_EXTERNAL_STORAGE

android.hardware.camera

Output:










Monday, May 16, 2011

Pick Image from Gallery set to Image View

package com.pickimagefromgal.activities;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Home extends Activity
{
    Button btnGal;
    ImageView ivGalImg;
    Bitmap bmp;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnGal         =     (Button)findViewById(R.id.btnGallary);
        ivGalImg     =     (ImageView)findViewById(R.id.ivImage);
       
        btnGal.setOnClickListener(new OnClickListener()
        {           
            @Override
            public void onClick(View arg0)
            {
                openGallery();               
            }
        });
    }
   
    private void openGallery()
    {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 1);
    }
   
  @Override
  protected void onActivityResult(int requestCode, int resultcode, Intent intent)
  {
      super.onActivityResult(requestCode, resultcode, intent);
     
      if (requestCode == 1)
      {
          if (intent != null && resultcode == RESULT_OK)
          {             
             
                Uri selectedImage = intent.getData();
               
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
             
                if(bmp != null && !bmp.isRecycled())
                {
                    bmp = null;               
                }
                               
                bmp = BitmapFactory.decodeFile(filePath);
                ivGalImg.setBackgroundResource(0);
                ivGalImg.setImageBitmap(bmp);             
          }
          else
          {
              Log.d("Status:", "Photopicker canceled");           
          }
      }
  }
}

main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/ivImage"
        android:background="@drawable/icon"   
        >
    </ImageView>
   
    <Button
        android:layout_width="wrap_content"
        android:text="Click To Open Gallary"
        android:id="@+id/btnGallary"
        android:layout_height="wrap_content">
    </Button>
   
</LinearLayout>

Manifast: 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pickimagefromgal.activities"
      android:versionCode="1"
      android:versionName="1.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Home"
                  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>

Out Put: