Monday, May 23, 2011

broadcast receiver with example

broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.
A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object. For more information, see the BroadcastReceiver class.


We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call then our receiver will be notified and log a message.
Create a new project "de.vogella.android.receiver.phone". We do not need an activity. Create the following "AndroidManifest.xml".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="de.vogella.android.receiver.phone" android:versionCode="1"
 android:versionName="1.0">
 <application android:icon="@drawable/icon" android:label="@string/app_name">


  <receiver android:name="MyPhoneReceiver">
   <intent-filter>
    <action android:name="android.intent.action.PHONE_STATE"></action>
   </intent-filter>
  </receiver>
 </application>
 <uses-sdk android:minSdkVersion="9" />


 <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</manifest> 
  
Create the following class "MyPhoneReceiver".
package de.vogella.android.receiver.phone;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyPhoneReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  Bundle extras = intent.getExtras();
  if (extras != null) {
   String state = extras.getString(TelephonyManager.EXTRA_STATE);
   Log.w("DEBUG", state);
   if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
    String phoneNumber = extras
      .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
    Log.w("DEBUG", phoneNumber);
   }
  }
 }
}

 

Gallery

A view that shows items in a center-locked, horizontally scrolling list.
The default values for the Gallery assume you will be using Theme_galleryItemBackground as the background for each View given to the Gallery from the Adapter. If you are not doing this, you may need to adjust some Gallery properties, such as the spacing.
Views given to the Gallery should use Gallery.LayoutParams as their layout parameters type.
In this tutorial, you'll create a gallery of photos and then display a toast message each time a gallery item is selected.
  1. Start a new project named HelloGallery.
  2. Find some photos you'd like to use, or use these sample images. Save the images into the project's res/drawable/ directory.
  3. Open the res/layout/main.xml file and insert the following:
    <?xml version="1.0" encoding="utf-8"?>
    <Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
  4. Open the HelloGallery.java file and insert the following code for the onCreate() method:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
    
        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }
    This starts by setting the main.xml layout as the content view and then capturing the Gallery from the layout withfindViewById(int). A custom BaseAdapter called ImageAdapter is instantiated and applied to the Gallery with setAdapter(). (The ImageAdapter class is defined next.) Then an anonymous AdapterView.OnItemClickListeneris instantiated. The onItemClick(AdapterView, View, int, long) callback method receives the AdapterView where the click occurred, the specific View that received the click, the position of the View clicked (zero-based), and the row ID of the item clicked (if applicable). In this example, all that's needed is the position of the click to show a Toast message that says the position of the item, using makeText(Context, CharSequence, int) and show() (in a real world scenario, this ID could be used to get the full sized image for some other task).
  5. Create a new XML file in the res/values/ directory named attrs.xml. Insert the following:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="HelloGallery">
            <attr name="android:galleryItemBackground" />
        </declare-styleable>
    </resources>
    This is a custom styleable resource that can be applied to a layout. In this case, it will be applied to the individual items placed into the Gallery widget. The <attr> element defines a specific attribute for the styleable, and in this case, it refers to an existing platform attribute, galleryItemBackground, which defines a border styling for gallery items. In the next step, you'll see how this attribute is referenced and then later applied to each item in the gallery.
  6. Go back to the HelloGallery.java file. After the onCreate(Bundle) method, define the custom ImageAdapter class:
    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;
    
        private Integer[] mImageIds = {
                R.drawable.sample_1,
                R.drawable.sample_2,
                R.drawable.sample_3,
                R.drawable.sample_4,
                R.drawable.sample_5,
                R.drawable.sample_6,
                R.drawable.sample_7
        };
    
        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.HelloGallery_android_galleryItemBackground, 0);
            a.recycle();
        }
    
        public int getCount() {
            return mImageIds.length;
        }
    
        public Object getItem(int position) {
            return position;
        }
    
        public long getItemId(int position) {
            return position;
        }
    
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);
    
            i.setImageResource(mImageIds[position]);
            i.setLayoutParams(new Gallery.LayoutParams(150, 100));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setBackgroundResource(mGalleryItemBackground);
    
            return i;
        }
    }
    First, there are a few member variables, including an array of IDs that reference the images saved in the drawable resources directory (res/drawable/).
    Next is the class constructor, where the Context for an ImageAdapter instance is defined and the styleable resource defined in the last step is acquired and saved to a local field. At the end of the constructor, recycle() is called on the TypedArray so it can be re-used by the system.
    The methods getCount()getItem(int), and getItemId(int) are methods that must be implemented for simple queries on the Adapter. The method does the work to apply an image to an {@link android.widget.ImageViewthat will be embedded in the Gallery. In this method, the member Context is used to create a new ImageView. TheImageView is prepared by applying an image from the local array of drawable resources, setting the Gallery.LayoutParamsheight and width for the image, setting the scale to fit the ImageView dimensions, and then finally setting the background to use the styleable attribute acquired in the constructor.
    See ImageView.ScaleType for other image scaling options.
  7. Run the application.

Date Picker

This class is a widget for selecting a date. The date can be selected by a year, month, and day spinners or a CalendarView. The set of spinners and the calendar view are automatically synchronized. The client can customize whether only the spinners, or only the calendar view, or both to be displayed. Also the minimal and maximal date from which dates to be selected can be customized.



To provide a widget for selecting a date, use the DatePicker widget, which allows the user to select the month, day, and year, in a familiar interface.
In this tutorial, you'll create a DatePickerDialog, which presents the date picker in a floating dialog box at the press of a button. When the date is set by the user, a TextView will update with the new date.
  1. Start a new project named HelloDatePicker.
  2. Open the res/layout/main.xml file and insert the following:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView android:id="@+id/dateDisplay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""/>
        <Button android:id="@+id/pickDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Change the date"/>
    </LinearLayout>
    This creates a basic LinearLayout with a TextView that will display the date and a Button that will open theDatePickerDialog.
  3. Open HelloDatePicker.java and add the following members to the class:
        private TextView mDateDisplay;
        private Button mPickDate;
        private int mYear;
        private int mMonth;
        private int mDay;
    
        static final int DATE_DIALOG_ID = 0;
    The first group of members define variables for the layout Views and the date items. The DATE_DIALOG_ID is a static integer that uniquely identifies the Dialog that will display the date picker.
  4. Now add the following code for the onCreate() method:
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            // capture our View elements
            mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            mPickDate = (Button) findViewById(R.id.pickDate);
    
            // add a click listener to the button
            mPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
            });
    
            // get the current date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
    
            // display the current date (this method is below)
            updateDisplay();
        }
    First, the content is set to the main.xml layout. Then the TextView and Button elements are captured from the layout withfindViewById(int). A new View.OnClickListener is created for the Button, so that when it is clicked, it will callshowDialog(int), passing the unique integer ID for the date picker dialog. Using showDialog(int) allows the Activityto manage the life-cycle of the dialog and will call the onCreateDialog(int) callback method to request the Dialog that should be displayed (which you'll define later). After the on-click listener is set, a new Calendar is created and the current year, month and day are acquired. Finally, the private updateDisplay() method is called in order to fill the TextView with the current date.
  5. Add the updateDisplay() method:
        // updates the date in the TextView
        private void updateDisplay() {
            mDateDisplay.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));
        }
    This method uses the member date values declared for the class to write the date to the layout's TextViewmDateDisplay, which was also declared and initialized above.
  6. Initialize a new DatePickerDialog.OnDateSetListener as a member of the HelloDatePicker class:
        // the callback received when the user "sets" the date in the dialog
        private DatePickerDialog.OnDateSetListener mDateSetListener =
                new DatePickerDialog.OnDateSetListener() {
    
                    public void onDateSet(DatePicker view, int year, 
                                          int monthOfYear, int dayOfMonth) {
                        mYear = year;
                        mMonth = monthOfYear;
                        mDay = dayOfMonth;
                        updateDisplay();
                    }
                };
    The DatePickerDialog.OnDateSetListener listens for when the user has set the date (by clicking the "Set" button). At that time, the onDateSet() callback method is called, which is defined to update the mYearmMonth, and mDay member fields with the new date then call the private updateDisplay() method to update the TextView.
  7. Now add the onCreateDialog(int) callback method to the HelloDatePicker class:
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
    This is an Activity callback method that is passed the integer ID given to showDialog(int) (which is called by the button'sView.OnClickListener). When the ID matches the switch case defined here, a DatePickerDialog is instantiated with the DatePickerDialog.OnDateSetListener created in the previous step, along with the date variables to initialize the widget date.
  8. Run the application.

Tuesday, May 10, 2011

What is the NDK?

The

Android NDK

is a toolset that lets you embed components that make use of native code in your Android applications.

Android applications run in the Dalvik virtual machine. The NDK allows you to implement parts of your applications using native-code languages such as C and C++. This can provide benefits to certain classes of applications, in the form of reuse of existing code and in some cases increased speed.
The NDK provides:
  • A set of tools and build files used to generate native code libraries from C and C++ sources
  • A way to embed the corresponding native libraries into an application package file (.apk) that can be deployed on Android devices
  • A set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5. Applications that use native activities must be run on Android 2.3 or later.
  • Documentation, samples, and tutorials
The latest release of the NDK supports these ARM instruction sets:
  • ARMv5TE (including Thumb-1 instructions)
  • ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for NEON/VFPv3-D32 instructions)
Future releases of the NDK will also support:
  • x86 instructions (see CPU-ARCH-ABIS.HTML for more information)
ARMv5TE machine code will run on all ARM-based Android devices. ARMv7-A will run only on devices such as the Verizon Droid or Google Nexus One that have a compatible CPU. The main difference between the two instruction sets is that ARMv7-A supports hardware FPU, Thumb-2, and NEON instructions. You can target either or both of the instruction sets — ARMv5TE is the default, but switching to ARMv7-A is as easy as adding a single line to the application's Application.mk file, without needing to change anything else in the file. You can also build for both architectures at the same time and have everything stored in the final .apk. Complete information is provided in the CPU-ARCH-ABIS.HTML in the NDK package.
The NDK provides stable headers for libc (the C library), libm (the Math library), OpenGL ES (3D graphics library), the JNI interface, and other libraries, as listed in the Development Tools section.

Friday, May 6, 2011

JSON Parsing in android

JSON


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.



JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.


JSON with android


org.json package available in android SDK which suports JSON parsing 


JSONObject
JSONArray



String json = "{"
         + "  \"query\": \"Pizza\", "
         + "  \"locations\": [ 94043, 90210 ] "
         + "}";

 JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
 String query = object.getString("query");
 JSONArray locations = object.getJSONArray("locations");




This is a very simple JSON String
{"key1":"value1","key2":"value2"}
In order to get values for it use JSONObject like this :
JSONObject json_obj=new JSONObject(your json string);<br>
String value1=json_obj.getString("key1");<br>
String value2=json_obj.getString("key2");
This is a slightly complex json string
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]
In order to extract values from this use JSONArray
JSONArray jArray=new JSONArray(your json string);<br>
for(int i=0;i<(jArray.length());i++)<br>
{
  JSONObject json_obj=jArray.getJSONObject(i);
   String value1=json_obj.getString("key1");
   String value2=json_obj.getString("key2");
}