Wednesday, June 26, 2013

Android App Development 2

Steps to add new activity in Android Application:

Register the activity in AndroidManifest.xml.
finish() is used to close the activity.
 



1) Activity which has launcher category and MAIN action
 will be showed on screen first.
This is called the main activity.

2) Menu
    Menu items can have shortcuts or icons with text.
    Icons are supported only in first 6 items.

By pressing menu button,menu will be displayed.

    2.1) options menu - 6 items are supported in single screen
              - if we have more than 6 items, last item will be shown as more...   
                          - while clicking more, it will show expanded menu  
           Options menu belongs to Activity.
       
    If we want to add options menu in our activity:
    we have to implement the following:
    while clicking menu key, onCreateOptionsMenu() fn will be invoked.

        1) onCreateOptionsMenu() returns true menu will appear on screen
                           returns false menu wont appear on screen
        2)onOptionItemSelected() - if we handled the selected menu item, return true
                 if we have not handled the selected menu item,return false.the base class version of
                          onOptionItemSelected() will be invoked
   
       
 
  menu.add(groupid,ItemId,order,menuText)


                
    2.2) context menu
               - will be displayed if we do long press on any view
           - belongs to the view
               - register the view by registerForContextMenu
           - Dont have support for icons or shortcuts
       implement:
        onCreateContextMenu()            
        onContextItemSelected()
   
        2.3) SubMenu
        - part of another menu item
                - it can be options menu or
              context menu
        - submenu is supported only one level...
          Nested submenus are not supported
            implement:
        onCreateOptionsMenu()
            SubMenu fileMenu =menu.addSubMenu("File");               
        SubMenu editMenu = menu.addSubMenu("Edit");
                fileMenu.add(itemId,"new");
        fileMenu.add(itemid,"open");
 
   

Develop sample application for context menu and submenu.

Notifying user:
===============
    1)Toast notification
        - no user interaction
        - used from activity or service
        - Acivity stills active while displaying toast & responsive
        - Doesn't accept interaction events
        2)StatusBar notification
        - Persistent reminders
        - alert remains as long as user have not seen or visited it
        - need interaction from user
        - Ex: SMS, low battery,download status, once content is downloaded, download complete notification
        - used from activity or service

        it requires:
        -icon for the status bar
        -title,expanded message, expanded view
            -Pending intent triggered to launch the application or activity
        -on user action, we can launch activity or service or broadcast receiver
               

    2.1)Get a reference to the notification manager:
        NotificationManger mNotificationMgr=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    2.2)Create notification:
        String tickerText = "hello";
        Notification notification= new Notification(R.drawable.ic_launcher,tickerText ,System.currentTimeMillis());
    2.3)Define the notification's expanded message and Intent:
        //wrap the intent object inside pending intent
        Intent notificationIntent= new Intent(this,Myclass.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
        notification.setLatestEventInfo(this,contentTitle, contentText,pendingIntent);

        For service:
            PendingIntent.getService()
        For broadcast:
            PendingIntent.getBroadcast()

       
    2.4)Pass the notification to Notification manager
        mNotificationMgr.notify(notificationId,notification);   

        once application is launched, clear the notification in system.   
       
   
    who will trigger the pending intent in notification ???
            It will be done by Notification manager.


    3)Dialog notification
        - used only from activity
        - Current Activity will be in Pause state
        - AlertDialog
            - max. selectable 3buttons
            - buttons appear on dialog bottom
            - checkboxes or radio buttons allowed
            -
   
        - ProgressDialog
        - DatePickerDialog
        - TimePickerDialog

    Add dialog to activity:
        1) implement onCreateDialog(dialogId)[create & return dialog]   
            Every dialog has its own unique id.
            Called only once
           
        2)when we want to display a dialog
           call showDialog(dialogId);
            showDialog internally calls onCreateDialog(withIdArg)
        3) remove dialog can be done by removeDialog();

        AlertDialog.Builder class can be used to configure the dialog properties.
        By default all dialogs are cancelable.




   Two types of dialog box:
    1) Spinning wheel dialog- Dont know when it will end we will go for the spinning wheel dialog
    2) Progress dialog - know when the task will end
                 For download status, we are sure when download will end.
        horizontal

Spinning Wheel dialog:
   
    boolean iscancelable= true;
         ProgressDialog pDialog = ProgressDialog.show(MyActivity.this,"","Loading please wait..",isCancelable);
    when everything ends,
    call progressDialog.cancel()...

   
Horizontal dialog:
   


Adapters and Adapter views:
=============================
Adapter
   1)provides data to AdapterView [listview,gallery,spinners];
   2)responsible for making a View for each item
 
Two types of adapter:
    1) array adapter
    2) cursor adapter   
     
Adapter:
   1)supply data
   2)handles UI view

   listView.setAdapter()

Adapter base class:BaseAdapter
ArrayAdapter - Array data
SimpleCursorAdapter - handle database related data


Intent:
    -message passing mechansism that workes  both within application and between applications
Types of intents:
    1) Explicit intent- launching the activities of same application
        2) Implicit intent -launch the activity of other application



Example for implicit intent:
    Intent i = new Intent(Intent.ACTION_DIAL,Uri.parse('tel:555-1234"));
    startActivity(i);

Explicit intent syntax:
    Intent i = new Intent(Action, data)
    Action - mandatory
    data - optional

 It will find out the activity which can perform the ACTION on that data.if it finds the activity,
it will launch activity.

  Resolving implicit intent at runtime is called as Intent resolution.


Android registry:
====================
    contains classname action and datatype.

At run time, it looks into the registry & decide which activity launch.
If  multiple activities can perform the same action, Android will popup the dialog to user for selecting the right application.

If there are no application match found, then it will crash and give force close dialog.


Any ways to update Android registry??


Native android actions:
    ACTION_ANSWER
    ACTION_DIAL
    ACTION_EDIT - Activity that can edit data specified in the intent
    ACTION_PICK - pick an item from the content provider in the intent
    ACTION_VIEW-Activity that can view data specified in the intent
    ACTION_SENDTO
   
Contacts DB is exposed publicly to others by content providers.

Intent i = new Intent(ACTION_VIEW,Uriparse("http://google.com"); #launch the browser

Intent i = new Intent(ACTION_VIEW,Uriparse("tel:123456");#???


From parent activity, we can get child activity information if

 1)child activity launched with startActivityForResult()
 2)Once the child activity is closed, it will triggers the parent activity's
  onActivityResult()
    requestcode let us know from which child activity, we are getting results

 
IntentFilter:
===============
    intentfilter contains
        1)action
        2)category
        3)data

        Activity.Action
       

In AndroidManifest.xml
    <data androidscheme="abc" />

During installation, Android manifest file is checked. Installer will update the android registry.
Activity without intentfilters, we can say without private Activity which can be launched only from that application.

Activity with intentfilters can be accessed from any application.


refer OpenIntents.org defines the already available intents from other apps in google play or playstore.
openintents.org

Broadcast Receiver:
===================
  Android uses broadcast intents to broadcast system events like battery low,battery level, network connections etc

 Intent i = new Intent(action);
 sendBroadcast(i);
   
 i-Broadcast intent
 action-Broadcast action


  Mainly used from services

Native Android Broadcast Actions:
    Android broadccasts intents for many of the system services primarily to
track device status changes.

   
1)ACTION_BOOT_COMPLETED
2)ACTION_CAMERA_BUTTON
3)ACTION_MEDIA_MOUNTED
4)ACTION_MEDIA_EJECT
5)ACTION_DATE_CHANGED
6)ACTION_TIME_CHANGED

Time limit in onReceive() is 10 seconds.

Two types of broadcast:
1)order broadcast
    based on highest priority
2)

Broadcast is not visible to user whereas status bar notification is visible to user.

In AndroidManifest.xml, register the broadcast action for broadcast receiver.

Static registration


Register by code:
===================
Dynamic registration of broadcast receiver:

if register it in code, usually add it in OnCreate() of launcher activity.

IntentFilter filter= new IntentFilter("com.test.action.newLocation");
LocationUpdater recvr= new LocationUpdater();
RegisterReceiver(recvr,filter);


Unregister by code:
=================
unregisterReceiver(recvr); #if forgotten, it will give


Diff static registration and dynamic registration:
===================================================

static registration:
   If my application is not available, it will be able to receive broadcast action
   Ex; BOOT_COMPLETED

Dynamic registration:
====================
   If my application is not available, it wont be able to receive broadcast action

For system events, go for static registration.
For Application specific events, go for dynamic registration.


Same BroadcastReceiver can be used to register for multiple broadcast intents;


 In onReceive()
{
    string action= intent.getAction();
    if(action == BOOT_COMPLETED)
    {
    handleBootCompleted();   
    }
    else if(action ==BATTERY_LOW )
    {
    handleBatteryLow();
    }
         
}


Service:
===========
two ways of service:
    1)background and long running task &  No UI
    2use service as interface [IPC]
======>    AIDL


Activity and Service is running in the same thread.
while launch a service, new thread will not be created.
Service is not a separate process, it is belonging to the activity process and running in the same thread.


Service:
  1)Create service class
  2)register the service in AndroidManifest.xml
  3) if you want to make it public, register the intent filter for the service so that others can use ur service



Creating a service:
 1)startService & stopService
 2) In case of interface or IPC, use bindService(), unbindService() fn


  single service instance used for serving multiple applications.
if one application is using the service, onCreate() onStart() is called.
Second application is creating the service, then it wont call onCreate(), onStart() will be called repeatedly.


Always create thread

1)less chance the service will get killed compare to background process
2)Even though the activity will be killed, still the service will run in background


Actvity will start the service.
Service will broadcast the receiver.
Activity will receive the broadcast.
           


       
   

       








No comments: