Tuesday, September 6, 2011

Custom Notifications in Notification Bar in Android

Following Example will illustrate on Creating and sending Custom Notifications in Notification bar and clearing the created notifications too.

The Documents regarding the Notification Manager and Notification bar can be found here and here.
I'm using this concepts and here is the working example for the same.

Following is the basic screen shot for the application.


On Pressing the "Trigger Notification" button an Notification will be seen in the Notification bar saying "One Notification Received!! " as follows:


Now, expand the Notification window by dragging, you will see the notification as follows,


Start with creating a new Android Project in Eclipse, and following is the layout and Activity code for the application.

Layout Code i.e. 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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Notification Sample, Click On Button To See A Sample Notification Above!!"/>
    
<Button android:text="Trigger Notification" 
android:id="@+id/btnNotification" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>
<Button android:text="Clear Notification" 
android:id="@+id/btnClearNotification" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>   
        
</LinearLayout>


Following is the Activity Code for the Application (NotificationExample.java):



package com.mayuri.notification.example;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;


   public class NotificationExample extends Activity {   

Button btnNotification,btnClearNotification; 


int NOTFICATION_ID = 198990; 
NotificationManager nm = null;          
@Override    
public void onCreate(Bundle savedInstanceState) {        


super.onCreate(savedInstanceState);        
setContentView(R.layout.main);
        btnNotification = (Button) this.findViewById(R.id.btnNotification);
        btnNotification.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

nm = (NotificationManager)
getSystemService(NotificationExample.this.NOTIFICATION_SERVICE);
String MyText = "One Notification Received!!";
String TitleText = "Message From Mayuri";
String NotiText  = "Hope you liked My Example :-)";

Notification mNotification = new 
Notification(R.drawable.icon,MyText,System.currentTimeMillis());
Intent MyIntent = new Intent( getApplicationContext(), NotificationExample.class);

MyIntent.putExtra("extendedTitle", TitleText);
MyIntent.putExtra("extendedText" , NotiText);         


PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent,0);                    mNotification.setLatestEventInfo(getApplicationContext(),TitleText,NotiText, StartIntent);                                       
nm.notify(NOTFICATION_ID , mNotification );      
        }
});      
             
        btnClearNotification = (Button) this.findViewById(R.id.btnClearNotification);
        btnClearNotification.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (nm!=null){
nm.cancel(NOTFICATION_ID);
}
}
});      
    }
}



In the above example, on clicking the button, Clear Notification, will clear the notification from the Notification bar.


I hope my example was useful.


Happy Coding :-))


Mayuri

Friday, June 24, 2011

Simple Dialogs and Popups in Android

Following Article shows creating a Simple Dialogs and Pop ups in an Android Application.

Following are the Three Types of Dialogs illustrated in this Sample Application.
  • Alert Confirmation
  • Dialog with Select List
  • Progress Dialog
Following is the basic screenshot of the Application:


From the Above Screen Shot, on Clicking the each of the buttons i.e. Alert, Select List and Progress Dialog, their corresponding Dialogs are displayed.

Following is the Screen Showing Alert Confirmation Dialog:


Following is the Screen Showing Select List Dialog:


Following is the Screen Showing Progress Dialog:



Start with creating a Sample Application in Android (in Eclipse off course ) and following is the respective layout and Activity code for the Application:

Layout Code i.e. 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">
    
<TextView  
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:text="@string/hello"/>
    
<Button 
android:text="Show Alert Sample" 
android:id="@+id/btnAlertSample" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>
<Button 
android:text="Show List Dialog Sample" 
android:id="@+id/btnListSample" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>
<Button 
android:text="Show Progressbar Sample" 
android:id="@+id/btnProgress" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>
</LinearLayout>

Following is the Activity Code for the Application (DialogSample.java):

package com.mayuri.dialogs.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; 
import android.widget.Toast;
import android.view.View.OnClickListener;
public class DialogSample extends Activity {
Button btnAlert, btnList, btnProgress;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
      btnAlert = (Button)this.findViewById(R.id.btnAlertSample);
      btnList = (Button)this.findViewById(R.id.btnListSample);
      btnProgress = (Button)this.findViewById(R.id.btnProgress);     
       
      btnAlert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(DialogSample.this);
builder.setMessage("Are you sure you want to exit?")
      .setCancelable(false)
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
              DialogSample.this.finish();
          }
      })
      .setNegativeButton("No", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
               dialog.cancel();
          }
      });
AlertDialog alert = builder.create();
alert.show();
}
});       
   btnList.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final CharSequence[] items = {"Mango", "Orange", "Banana"};
AlertDialog.Builder listBuilder = new AlertDialog.Builder(DialogSample.this);
listBuilder.setTitle("Select A Fruit");
listBuilder.setItems(items, new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int item) {
       Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
   }
});
AlertDialog alertList = listBuilder.create();
alertList.show();
}
}); 
       
   btnProgress.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialog progressDialog = ProgressDialog.show(DialogSample.this, "Progress Dialog Example",                      "Please wait...", true);
}
});   

    }
}


Above code is very simple as onClick listeners is added to each of the button and the corresponding dialog is called.

I hope this Article was useful.

That's All from my end for now.

Happy Coding :-))

~Mayuri


Tuesday, June 21, 2011

Simple Example on How to Create Menus In Android

Following article will be helpful in creating custom Menus in Android.

Menus in Android Phones are those which Appears on clicking the leftmost button, which is at the left side of the home screen, Menus Appear at the bottom most area of the Screen, Example as illustrated in the following screen shot.



Following Example will help you to create your own custom menus required for your Application, (Check Screenshot below)



Start with creating the xml file named menus.xml in <application_name>\layout\ folder for defining the Menu List as follows:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_new"          
          android:title="New" />
          
     <item android:id="@+id/menu_about"         
          android:title="About" />
               
    <item android:id="@+id/menu_help"         
          android:title="Help" />
</menu>

In the above xml, I have simply defined three menus, 'New', 'About' and 'Help', also defined their respective Title and Ids.

Next Step is to call this file in our main Activity Class, this is done as shown in the code for the main Activity class as follows:


package com.mayuri.menuexample;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MenuSample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);         
       
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menus, menu);
        return true;
    } 
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
       
        switch (item.getItemId())
        {
        case R.id.menu_about:
            Toast.makeText(MenuSample.this, "You Clicked About", 3000).show();
            return true;
        case R.id.menu_help:
            Toast.makeText(MenuSample.this, "You Clicked Help", 3000).show();
            return true;
        case R.id.menu_new:
            Toast.makeText(MenuSample.this, "You Clicked New", 3000).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

The method onCreateOptionsMenu is required to call the defined menus.xml file with the help of the class 'MenuInflater'.

Then an 'onOptionsItemSelected' is defined on each menu items to get the selection events for the each of the menus and the corresponding Toast Popup is displayed for all the three menu selected events.

Following screenshot shows the Diplayed Toast Popup on the selection of the menu 'Above'


This was the basic example of creating custom menus in Android, Hope it was useful, So thats all from my end for now!

Happy Coding..  :-))

~Mayuri

Wednesday, June 1, 2011

Basic Example of Including a Google Map In Your Application

Google Maps is one of the best Web Mapping Services offered by Google. As I'm the biggest fan of Google's products and services, I love to use Google Maps. It has the wide rage of Functionalites, Options, events, types etc to suit our requirements.

Following code is the simple example to include Google Maps in our Applications.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"> </script>
<script type="text/javascript">
var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(21.18099395, 72.81892314999999);  
  var myOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }  
  map = new google.maps.Map(document.getElementById("mymap"), myOptions);
  var marker = new google.maps.Marker({
      position: myLatlng,
      title:"You Are Here Now!!"
  });    
  marker.setMap(map);    
}
</script>
</head>
<body onload="initialize()">
  <div id="mymap" style="width:1000px; height:500px;"></div>
</body>
</html>

The output of the same is as follows:

Explanation:

To start with with HTML part, we need to define a container to include Google maps in our HTML page. In this example I have taken a div by the name "mymap" as the base container to include Google map. The Height, width or any other css properties of the div can be set as per the requirements.

Now comming to the Javascript section, we need to include the Google Maps source js as follows:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"> </script>

The new instance of the LatLng is created by taking the values of Latitude and Longitude as the parameters, here I have taken the values of Latitude and longitude of my current location, it could vary as per the location.

Then the options array by the name "myOptions" is initilized, by the following parameters:

  • 'zoom' includes the zooming levels of the maps. the more is the zoom level the more we go towards the interior of the location or place.
  • 'center' indicates the center most position of the Map, here I have given the parameters as my current location so the specified location will become the center most location.
  • 'mapTypeId' here I'm using ROADMAP, other options also includes SATELLITE, HYBRID and TERRAIN.

Thus, the map object is initialized by the above specified parameters and the id of the div container of the HTML page.

Then the marker object is placed in the map at the Latitude and the Longitude position specified with the ToolTip specified (see screenshot) as "You Are Here Now!!".

This was the very basic example, of the Map with the marker, you could have multiple markers, events to the markers, Popups etc, and other multiples things to suit your requirements.

Thats all for now from my end.

Happy Coding!! :-))

~ Mayuri



Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here


Tuesday, May 31, 2011

Creating a Remote Background Service In Android.

How to create a basic Remote Services in Android:

Following article will illustrate how to create a simple basic Remote Service in Android that will run in the background, and which will be triggered by the activity.

Since last so many days I was struggling badly on creating a Remote background service in Android, For the same I found various articles, also went through many blogs, the docs for the android developers etc. Whatever articles I went through, the example given in them had some service task performing, which was confusing me, however I wanted a clear framework and design starting from a strach to implement the background service, and so is this post,

Following atricle will illustrate the basics of creating a Remote Background Service in Android.

The very first step is to create a new Android Project in Eclipse.

Then add the Service Interface in a '.aidl' file.

AIDL  (Android Interface Definition Language) is similar to the java interface with the method signature defined.

Following are the contents of 'RemoteServiceExample.aidl' file:

package com.example;

interface RemoteServiceExample {
      void doServiceTask();
}

Once after creating above file whenever you build the workspace, Eclipse generates the corresponding java interface, you can see the same in the 'gen' section. Also a care is to be taken that this is the autogenerated file and no need to modify the same.


Following is the code for the Core Service implementation:


package com.example;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder; 
import android.os.RemoteException;
import android.util.Log;


public class CoreRemoteService extends Service{
@Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return coreRemoteServiceStub;
}  

private Stub RemoteServiceExample.Stub coreRemoteServiceStub = new RemoteServiceExample.Stub() {
public void doServiceTask() throws RemoteException {
/// Write here, code to be executed in background
Log.d(getClass().getSimpleName(),"Hello World From Remote Service!!");
}   
};

@Override 
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(),"onCreate()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getSimpleName(),"onDestroy()");
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(getClass().getSimpleName(), "onStart()");
}
}

Form the above code have a look at the onBind() method, it returns the IBinder object. IBinder will represent the implementation of the remote service.
The implementation of the method of the 'aidl' interface (doServiceTask() in this example) is provided by the Stub class of the RemoteServiceExample.
In the method doServiceTask() will have the list of all the task to be executed while service is running. It can have the other method calls or the Code blocks to be executed. In the example I'm just printing a single line log "Hello World From Remote Service!!".

Now, coming to the main Activity class which will trigger the service, or we can say that the Activity will act as Client which can connect to the above created service. Have a look at the code for the same as follows:

package com.example;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;


public class ExampleRemoteService extends Activity {
RemoteServiceExample remoteServiceExample;
private RemoteServiceConnection conn = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        Intent i = new Intent();        
i.setClassName("com.example", "com.example.CoreRemoteService");
startService(i);
conn = new RemoteServiceConnection(); 
bindService(i, conn, Context.BIND_AUTO_CREATE);        
    }       
    class RemoteServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className, IBinder boundService ) {    
        remoteServiceExample = RemoteServiceExample.Stub.asInterface((IBinder)boundService);        
        try{
        remoteServiceExample.doServiceTask();
        }catch(RemoteException e){        
        e.printStackTrace();
        }        
          Log.d( getClass().getSimpleName(), "onServiceConnected()" );
        }


        public void onServiceDisconnected(ComponentName className) {          
  Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
        }
    };
    
}

Here I haven't kept any button to explicitly start the service, instead the service is started as the Activity is created.
An object of Intent is created, where the classname of the same is set, and then this object is passed as an argument of startService() method.
The class name set in the Intent is the fully qualified class name of the Class which extends 'Service', here in the example, 'CoreRemoteService' class.
Now the class 'RemoteServiceConnection' which implements 'ServiceConnection' interface is created to establish the connection with the remote service.
The object of this class along with the Intent object is passed as an argument in bindService() method.

Finally, we need to add a reference of the remote service created in Android Manifest file as follows:
<service android:name=".CoreRemoteService">
</service>

Now you are done with creating the remote background service.

As you install the apk and run on an Android Device or Emulator, service Prints in the log "Hello World From Remote Service!!".

Also you can check in your device, Settings>Applications>Running Service, the name of your service in the running services list.

So this was the very basic example of creating a remote background service in Android.

Thats all from my end!

Happy Coding!! :-))




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here



Animated Container in Flutter

Please check this flutter video tutorial for detailed example and implementation of Animated Container in Flutter.