Saturday, September 8, 2012

Android Notifications Syestem

Android Notifications System is a very good feature in android OS. This provide user with the very recent notifications to the user each time when notification activity is called. A status notification system is added an icon to the status bar with a ticker text messages. When user click or touch the ticker android fires an Intent This activity is called the notification. Having  a full description or link of the other activity. You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.

Android notification is used to run a background service of any applications to run in the background and It never call its activity by itself human interaction is needed to perform any operation on the notifications. After clicking on it It will fire an other activity.
Notification bar is something look like this..


                                        Figure:1 Notification status bar

                                    Figure:2 Notification Bar with message


Notification can be provided to the user by any of the following ways.
  • ·         Status Bar Notification
  • ·         Vibrate
  • ·         Flash lights
  • ·         Play a sound
 While the notification is generated on the applications then it will only allow the user to interact with the other activity.

To create any notification we just needed two classes.
  • Notification - This class having all the property related to the notification status bar like what icon we have to show on the notification bar and how much time the notification will show means how much duration the notification should show.
  • NotificationManager - Thsi class an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManager but you can retrieve a reference to it by calling the getSystemService() method.
After using all these we just need to pass the notification object to the notify()  function this will run your notification.

While all these we have done now we have to make the activity where we have to define that what information we have to show on the activity. This is done by calling the method setLatestEventInfo() on the notification object.

Now let us see the example which i have given over here you can download the example  source code by just clicking here.

How the example is working--

Step 1: Make object for NotificationNanager.

            private NotificationManager myNotificationManager;
      …
myNotificationManager =
      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

Step 2: Create a notification object along with properties to display on the status bar like what image should display and duration for display

final Notification notifyDetails =
new Notification(R.drawable.android,"I am Alert, Click me!",System.currentTimeMillis());

Step 3:  In the details I have added the intent which will transfer you to the google website by the browser http://www.google.com

Context context = getApplicationContext();
     
CharSequence contentTitle = "Notification Details...";
     
CharSequence contentText = "Browse google Site by clicking me";
Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.google.com"));
     
PendingIntent intent =
      PendingIntent.getActivity(SimpleNotification.this, 0,
      notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
Step 4: Now the stage is set. Notify.
       
      myNotificationManager.notify(NOTFICATION_ID, notifyDetails);

Note that all of the above actions(except getting a handle to the NotificationManager) are done on the click of a button “Start Notification”. So all the details go into the setOnClickListener() method of the button.
Similarly, the notification, for the example sake is stopped by clicking a cancel notification button. And the code there is :
mNotificationManager.cancel(NOTFICATION_ID);

Now, you may realize that the constant NOTIFICATION_ID becomes the way of controlling, updating, stopping a current notification that is started with the same ID.

For more options like canceling the notification once the user clicks on the notification or to ensure that it does not get cleared on clicking the “Clear notifications” button, please see the android reference documentation.

Friday, August 24, 2012

Passing Data Between Two Activities

In this post we will discuss about how to pass data between two activities. This is very important feature in perspective of the any application that it always needed to pass data between two activities. Here we will use two activities two pass the data first calling activity is called as the parent activity and other is invoked activity child activity.

For simplicity sake, We use an explicit intent for invoking the child activity. For simple invocation without expecting any data back, we use the method startActivity(). However, when we want a result to be returned by the child activity, we need to call it by the method startActivityForResult(). When the child activity finishes with the job, it should set the data in an intent and call the method setResult(resultcode, intent) to return the data through the intent.

When the parent activity expecting result from the invoked activity. The parent activity should have overridden the method onActivityResult(…) in order to be able to get the data and act upon it. 

After the setting up the set activity setResult(...) please call finish() function to return to the parrent activity.

Here we need two methods to impliment on the parrent activity.

  1. startActivtyForResult(..)
  2. onActivityResult(..) 
The child activity must execute its line of codes after then it have to call the following two functions.
  1. setResult(..)
  2. finish()
You can download the working example from here

Here in this example we can see easily our calling activity having two buttons to view He or She. Either selecting one of them HeAcitivty or SheActivity which display a list using listview of selected type of objects. The user can select any of the object then the object will return it to the parent activity with data.


Since we are expecting to get back the selected object, the calling Activity’s code is like this:
     Intent HeIntent = new Intent();                heIntent.setClass(Home.this,HeActivity.class);
startActivityForResult(heIntent,HE_SELECT);
where HE_SELECT is just a constant to help us identify from which child activity the is result obtained, when there is more than 1 child activity, as in this case.

At this point the control is handed over to the BooksActivity. This displays the list of books and the user can scroll through and select a book. When the user selects a book, the selected book needs to be passed back to the CallingActivity. This is how it is done:
      Object o = this.getListAdapter().getItem(position);
      String book = o.toString();
      Intent returnIntent = new Intent();
      returnIntent.putExtra("Selected He",book);
      setResult(RESULT_OK,returnIntent);       
      finish();

The first 2 lines show how to get the selected he from the ListView. Then, you create a new intent object, set the selected book as an extra and pass it back through the setResult(…) method call. The result code is set to RESULT_OK since the job has been successfully done.  After that the finish() method is called to give the control back to the parent activity.

In the parent, the method that gets the control is onActivityResult(…)
protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
      switch(requestCode) {
      case HE_SELECT:
            if (resultCode == RESULT_OK) {
                String name = data.getStringExtra("Selected He");
                Toast.makeText(this, "You have chosen the He: " + " " + name, Toast.LENGTH_LONG).show();
                break;
            }
      ……….
      }
      }  

Here you notice that the HE_SELECT constant is used to act upon the result. If the result code is RESULT_OK, we take the book selected from the “extra” of the intent that is returned from the child activity. data.getStringExtra("SelectedHe") is called to and the name returned is displayed through a Toast.

Monday, August 20, 2012

Simple steps to make android development enviroment

Simple steps to make android development enviroment

1): First of all go to you browser and then search "Android system Requirement".
     Because it will tell you which software version you needed actually.
     Please follow the following link: http://developer.android.com/sdk/index.html

2): Download latest JDK with JRE (JDK 7 preferably )
      Please use the following ink to download the latest JDK version:
     http://www.oracle.com/technetwork/java/javase/downloads/index.html

3): Download android SDK (Software development kit)
     You must have to download the android software development kit
      use the following link to download it: http://developer.android.com/sdk/index.html

     a): Now install sofware
     b): Now install Android-platform tools (from server)
     c): Now install android SDK tools (from server)
     d): Dowonload specific required android API as you required to install







    After installation you will see the following image


4):  Now Download eclipse(Please check eclipse as per system
requirement ) version is most important thing so please check the
specific version. Please download eclipse 4.2
link: http://www.eclipse.org/downloads/

5): After downloading eclipse now Open eclipse as administrator and
then do following steps.

    a): Go to Help => Install New S/W
    b): Download ADT Plugin from server android.
    c): Click on "Add" Button
         Put the name "ADT Plugin"
         Now target (browse) your adt plugin zip file dont needed to
unzip the file
         Now click 'ok'
    d): Just 'check' the sdk Android option do not check the "NDK"  checkbox.
    e): follow the steps and finish.



6): Now your eclipse with restart now start working with android development.

Saturday, June 23, 2012

Pre-Packaged Applications | Android Tutorial for Beginners

There are many applications that are pre-packaged in the android platform that can be reused by the other custom applications. As we have stated in the previous  part 3. Implicit intents there we have provided the example of these types of one application related to contact application of android.


In this part of tutorial we will explore that how we can use the pre-packaged applications using impliocit intents. In these types of application we will just call the pre-packaged application using intents and pass them to the activity and after then we will start our activity with the startActivity() method. However, for each of these intents, the platform find the most befitting activity and invoke the same:

1. Call a number(Dial a number via application)
      Intent callNumber = new Intent();
      callNumber.setAction(android.content.Intent.ACTION_CALL);
      callNumber.setData(Uri.parse("tel:123456789"));
startActivity(callNumber);

This will call the number 123456789.If you want to call any number you want then you have to just add a edit text control then pass the desired value to the Uri.parse() method then it will dial your specified number.


 
2. Browse the web for a given url:

      Intent searchText = new Intent(Intent.ACTION_WEB_SEARCH);
      searchText.putExtra(SearchManager.QUERY, "Android Demo);
      startActivity(searchText);

This will start the google search  engine to search the specified string "Android Demo" and the get back the result on the screen. here the same thing as above specified in the dialed number application you can define a edit text control the pass the desired string to the appropiate space in the putExtra() method then the same result will show on the screen.


3.  View google maps for a given location(find out any location)

      Intent searchLocation = new Intent(Intent.ACTION_VIEW, 
      Uri.parse("geo:0,0?q=India"));
startActivity(searchLocation);

This will show the "India" location on the Google map. You can repeat the smae method for the edit text to search your desired location.


4. View Contacts on the phone(Navigate to view contacts)

Intent contacts = new Intent();
      contacts.setAction(android.content.Intent.ACTION_VIEW);
      contacts.setData(ContactsContract.Contacts.CONTENT_URI);
      startActivity(contacts);


I have created an Android eclipse project which showcases all of these examples by taking inputs from the end user. You can access the same here.



Wednesday, June 20, 2012

Fundamental Android- For Beginner (Tutorial 1)

Fundamental Android- For Beginner (Tutorial 1)

Hii Friends this is the first tutorial in which I will explain you new paradigms introduced by the Android platform for developers. 

This part will just explain you the fundamental block of the android and latter part of the tutorial will explain you the high standard programming in the andoid, more to drive home to concept than to show any great programming skills.

Android is working on the  four building/ blocks. From the perspective of the developer we can categories as follows:-
1. Activities
2. Services
3. Broadcast Receivers
4. Content Providers.

The Communication between the above mentioned components is through :-
1. Intents
2. Intent Filters

The user Interface for interaction is called:- 
1. Views
2. Notifications

Get a Brief look of above mentioned syntax's:- 

Activity is the basic building block of every visible android application. It provides the means to render a UI. Every screen in an application is an activity by itself. Though they work together to present an application sequence, each activity is an independent entity. Any application can not be imagine without an activity. An activity can also be stated as a page which is shown at the front end when the application is running.



Service is another building block of android applications which does not provide a UI. It is a program that can run in the background for an indefinite period. It is a very powerful feature in the android which is used to do any process in the background without intervention of the user. Like login to any application in background and show some other activity at the front end.

Broadcast Receiver is yet another type of component that can receive and respond to any broadcast announcements. Means if you have used the android phones or tablets then you have may times seen that many notification is coming on the notification bar these notification is get by the Broadcast receiver and shown at the front end.


Content Providers are a separate league of components that expose a specific set of data to applications. Means its a set of data which you used to be process and want to show to the user.


While the understanding and knowledge of these four components is good enough to start development, the knowledge of the means of communication between the components is also essential. The platform designers have introduced a new concept of communication through intents and intent filters. Intents are used for the communication between ll the above component stated they passed the data between each component with the help of some variable.



Intents are the messages that passed between the components, So we can say that it is very similar to the API where the API is used to pass data and get some response as same here it  passes the data with the help of some variable and nothing other more stress is needed there to accomplish this task.
However, the fundamental differences between API calls and intents' way of invoking components is
1. API calls are synchronous while intent-based invocation is asynchronous (mostly)
2. API calls are bound at compile time while intent-based calls are run-time bound (mostly)



Intents are of two types Implicit intents and explicit intents. Both will explain in the later posts.


Intent is a bundle of information, a passive data structure that holds an abstract description of the operation to be performed. (or in the case of broadcasts, a description of an event that has happened and is being announced).

Tuesday, June 19, 2012

Explicit Intent | Android Tutorial for Beginners

Explicit Intent I have described  intents earlier. Here we will discuss about intents, Intents are the methods to make a communication between two activities. means they used to pass data from one activity to other with the help of some variables.

There are 2 types of intents that Android understands.
1. Explicit Intent
2. Implicit Intent

In an Explicit intent, you actually specify the activity that is required to respond to the intent. In other words, you explicitly designate the target component(Activity). This is typically used for application internal messages.
Like we have to pass data from one activity to other activity to accomplish certain processing we used explicit intents.

In an Implicit intent (the main power of the android design), you just declare an intent and leave it to the platform to find an activity that can respond to the intent. Here, you do not declare the target component and hence is typically used for activating components of other applications seamlessly.


Now to explain intents in more detail you can download my example from here.


        Button invokeIntent = (Button)findViewById(R.id.invokeintent);
       
invokeIntent.setOnClickListener(new OnClickListener() {
        

        
public void onClick(View v) {
        
Intent explicitIntent = new Intent(InvokingActivity.this,InvokedActivity.class);
         startActivity(explicitIntent);
        
}
        });

 Note: Here the InvokingActivity activity this class have the layout main.xml and the  InvokedActivity this activity have the InvokedActivity.xml file for there layout. both of the layout you can make by using eclipse.

 In the next part of the series, we will see how to work with implicit intents which also needs us to understand intent-filters.

Friday, June 15, 2012

Eclipse Set up and New Android Project

Eclipse Set up and New Android Project

The first steps of configuring Eclipse to create android applications and the steps involved in creating a first android project are very well described in this blog at the screencast site. Hence I am not repeating the same here.

By using the following link you can easily able to start working with the application in your android enviroment.

Saturday, June 9, 2012

Implicit Intent | Android Tutorial for Beginners



We have seen in the last post about the explicit intents with a very simple example. now we will move to the more interesting concept implicit intents.

This require more theoretical aspects to understand it more clearly.


As we know that, explicit intents need a target activity to execute those type of intents. Here implicit intents does not need the target activity to define over here. also said that the android platform resolves as to which component is best suited to respond to an Implicit Intent. How does this happen?

 An Intent object has the following information (among other things like Component name, extras and flags) which is of interest for implicit intents:
  • Action
  • Category
  • Data 

So here the android platform compare these three (action, category and data) to something called "intent filters" are declared by probable target who are willing to accept implicit intents.i.e. 
Intent Filters are the way of any component to advertise its own capabilities to the Android system. This is done declaratively in the AndroidManifest.xml file.

      Note: Intent filters are always define in the android manifest files. Like our first activity which is called first time when application starts.
Some important points in Implicit intents.
  1. Implicit intent never define target components.
  2.  Components willing to receive implicit intent have to declare to handle their specific intent by declaring intent filters.
  3. A component can declare any number of Intent Filters 
  4. There can be more than one component that declares the same Intent Filters.
  5. You can set priority of intent filters to ensure order and responses. 
There are 3 tests conducted in order to match an intent with intent filters:
  1. Action Test
  2. Category Test
  3. Data Test 
 To see how the implicit intent is defined and working please download the code from here.

The ImplicitIntent Activity creates an implicit intent object "contacts". This intent object's component is not set. However, the action is set to "android.content.intent.ACTION_VIEW" and the data's URI is set to "ContactsContract.Contacts.CONTENT_URI". 

Such an intent matches with the intent filter declared by the view contacts native activity.
So, when you run this application, it displays the native UI for viewing the existing contacts on the phone!

Here is the relevant piece of code for the same:
            Button showContacts = (Button) findViewById(R.id.clickhere);
            showContacts.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Intent contacts = new Intent();
                contacts.setAction(android.content.Intent.ACTION_VIEW);
                contacts.setData(ContactsContract.Contacts.CONTENT_URI);
                startActivity(contacts);
               
            }
            });

In this manner many of the native applications can be seamlessly invoked as one of the activities in our applications through implicit intents.
Here is clearly shown that here no any other target component is defined. here is just a intent filter is set . on click of the button the internal contacts app is going to open.