Wednesday, December 21, 2011
C2DM Android
Here are the primary characteristics of Android Cloud to Device Messaging (C2DM):
• It allows third-party application servers to send lightweight messages to their Android applications. The messaging service is not designed for sending a lot of user content via the messages. Rather, it should be used to tell the application that there is new data on the server, so that the application can fetch it.
• C2DM makes no guarantees about delivery or the order of messages. So, for example, while you might use this feature to tell an instant messaging application that the user has new messages, you probably would not use it to pass the actual messages.
• An application on an Android device doesn’t need to be running to receive messages. The system will wake up the application via Intent broadcast when the message arrives, as long as the application is set up with the proper broadcast receiver and permissions.
• It does not provide any built-in user interface or other handling for message data. C2DM simply passes raw message data received straight to the application, which has full control of how to handle it. For example, the application might post a notification, display a custom user interface, or silently sync data.
• It requires devices running Android 2.2 or higher that also have the Market application installed. However, you are not limited to deploying your applications through Market.
• It uses an existing connection for Google services. This requires users to set up their Google account on their mobile devices.
Before we start to write client applications that use the C2DM feature, we must have an HTTPS application server that meets the following criteria:
• Able to communicate with your client.
• Able to fire off HTTP requests to the C2DM server.
• Able to handle requests and queue data as needed. For example, it should be able to perform exponential back off.
• Able to store the ClientLogin Auth token and client registration IDs. The ClientLogin Auth token is included in the header of POST requests that send messages. The server should store the token and have a policy to refresh it periodically.
C2DM imposes the following limitations:
• The message size limit is 1024 bytes.
• Google limits the number of messages a sender sends in aggregate, and the number of messages a sender sends to a specific device.
• Android Cloud to Device Messaging is currently an API in Labs, Google reserve the right to fundamentally change the service and associated quotas at any time.
• Support 2.2 and above OS versions.
• Mobile phone should have one Gmail active account (Gmail or android market).
Please note that by default, all new sender accounts are held to a development-only quota. This quota is sufficient for development and exploratory purposes. Before you launch a C2DM-enabled application to a large audience, you need to send the email (to Google from sender’s accounts) to discuss a production-level quota, including estimates on the number of devices and average messages per device.
How to add Notification bar in Android
public void sendNotification(IntentService caller, Class activityToLaunch, String title, String msg,
int numberOfEvents, boolean flashLed, boolean vibrate) {
try {
NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE);
// Create this outside the button so we can increment the number
// drawn
// over the notification icon.
// This indicates the number of alerts for this event.
final Notification notify = new Notification(R.drawable.notification_image, "", System.currentTimeMillis());
notify.icon = R.drawable.notification_image;
notify.tickerText = "New Alerts from App!";
notify.when = System.currentTimeMillis();
notify.number = numberOfEvents;
notify.flags |= Notification.FLAG_AUTO_CANCEL;
if (flashLed) {
// add lights
notify.flags |= Notification.FLAG_SHOW_LIGHTS;
notify.ledARGB = Color.CYAN;
notify.ledOnMS = 500;
notify.ledOffMS = 500;
}
if (vibrate) {
// add vibs
notify.vibrate = new long[] { 100, 200, 200, 200, 200, 200, 1000, 200, 200, 200, 1000, 200 };
}
Intent toLaunch = new Intent(caller, activityToLaunch);
PendingIntent intentBack = PendingIntent.getActivity(caller, 0, toLaunch, 0);
notify.setLatestEventInfo(caller, title, msg, intentBack);
notifier.notify(NOTIFY_1, notify);
} catch (Exception e) {
System.out.println("Error is " + e);
}
}
public static void clear(Activity caller) {
NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE);
notifier.cancelAll();
}
What is the Use of CustomItem in J2me
A CustomItem is customizable by subclassing to introduce new visual and interactive elements into
Forms.Say if you want the scrolling bar on to form u can use CustomItem for this purpose. CustomItem is very much like using low level into high level.Help full in J2me Application development.CustomItem have methods as
getMinContentHeight()Implemented by the subclass to return the minimum height of the content area, in pixels.
getPrefContentHeight(int width)Implemented by the subclass to return the preferred height of the content area, in pixels.
hideNotify()keyPressed(int keyCode)paint(Graphics g, int w, int h)repaint()traverseOut()Called by the system when traversal has occurred out of the item.
And much more....
Hope fully you can get the idea about CustomItem.
Working code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SimpleItemMIDlet extends MIDlet
implements CommandListener {
public void startApp() {
Form form = new Form("SimpleItemMIDlet");
form.append(new SimpleItem("SimpleItem"));
Command c = new Command("Exit", Command.EXIT, 0);
form.addCommand(c);
form.setCommandListener(this);
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT)
notifyDestroyed();
}
}
class SimpleItem extends CustomItem {
public SimpleItem(String title) { super(title); }
public int getMinContentWidth() { return 100; }
public int getMinContentHeight() { return 60; }
public int getPrefContentWidth(int width) {
return getMinContentWidth();
}
public int getPrefContentHeight(int height) {
return getMinContentHeight();
}
public void keyPressed(int key){
}
public void paint(Graphics g, int w, int h) {
g.drawRect(0, 0, w - 1, h - 1);
g.setColor(0x000000ff);
int offset = 0;
for (int y = 4; y < h; y += 12) {
offset = (offset + 12) % 24;
for (int x = 4; x < w; x += 24) {
g.fillTriangle(x + offset, y,
x + offset - 3, y + 6,
x + offset + 3, y + 6);
}
}
}
}
Above code is from
http://www.java2s.com/Code/Java/J2ME/SimpleItemMIDlet.htm
Interface Vs Inheritance
Interface Vs Inheritance
Interface: Like contract, which you must have to follow.
Inheritance: Like hierarchy of functionality.
Now where to use is important, And it totally depend upon situation
Which is appropriate to use depends on circumstances.
From my view:
Interface: If you want same behavior across unrelated classes.
Inheritance: Use when classes have same functionality.
Example:
Let’s say we have a class Singer that represents a human singer. Now, singer can also be a bird or a musical instrument like Piano etc too. If we make a Singer a class then we have to take care of the issue that inheriting Piano from Singer might not work as both classes don’t lie in the same category. Singer is a human (living being) whereas Piano is a non-living thing. So, instead of inheritance we can make an interface say Singable and we can implement it on Piano, Human, Bird etc.
OR
Bear extends Animal
Bird extends Animal
TeddyBear extends Bear implements Pet
Canary extends Bird
TweetyBird extends Canary implements Pet
A Pet is a set of defined behaviours, doesn't provide that behaviour as it will differ widely between your TeddyBear and your TweetyBird (TeddyBear might be cuddly but doesn't sing).
---------------------------------------------------------------
Benefits of inner classes in java
- Encapsulation
- Inner classes can access private fields and methods of the enclosing class. If you need a new class that has access to otherwise private data of an existing class, and you don't want to make that data available to the rest of the package (by removing the "private"), you can grant access to one other class by making that class in inner class of the class with the private data or method.
inner class is a class defined inside some other class (but you knew that). Inner classes are able to access the private members of their outer class instance.
A static inner class does not have this ability to access the privates of his outer class. This makes a static inner class very much like a regular class, and in many cases, using one of those mainly adds confusion over using a regular class without giving any real benefits.
Anonymous inner classes are often used because they save you having to explicitly define a class type. It's a shorthand, designed to save time while writing the code. Again, use with caution, cause they can make the code hard to understand.
Adding Command Action for Devices whose left / right Soft key is not working
When to use static Mehod and When to use non static
This is important to understand that when to use static method and when to use instance method:
Thumb rule for Static and Non Static is:
Use Static Method when your method is independent of state of the instance object.
Use Non Static when your method is depending upon state of the instance object.
Let’s understand this by example that is good for all of us:
public class MrHappyObject {
private String _mood = _HAPPY;
private final static String _HAPPY = "happy";
private final static String _ANNOYED = "annoyed";
private final static String _ANGRY = "angry";
private static int _instantiations;
public static void main( String [] args ) {
MrHappyObject obj1 = new MrHappyObject();
MrHappyObject obj2 = new MrHappyObject();
obj1.printMood();
obj2.printMood();
obj1.receiveHug();
obj2.receivePinch();
obj1.printMood();
obj2.printMood();
}
public void printMood() {
System.out.println( "I am " + _mood );
}
public void receivePinch() {
if( _mood.equals( _HAPPY ) ) {
_mood = _ANNOYED;
} else {
_mood = _ANGRY;
}
}
public void receiveHug() {
if( _mood.equals( _ANGRY ) ) {
_mood = _ANNOYED;
} else {
_mood = _HAPPY;
}
}
public MrHappyObject() {
_instantiations++;
}
public static int instances() {
return _instantiations;
}
}
First we will look when to use non static method.
In above example we have 2 object obj1, obj2.
Both are born happy.
Now we call receiveHug() by obj1, and receivePinch() by obj2.Both receiveHug() and receivePinch() are non static method and they depends upon state of the object.
So the final output is:
I am happy
I am happy
I am happy
I am annoyed
That is what we want as Hugging the MrHappyObject`s Object make him happy and
Pinching it make it annoyed. We got the desired result because receiveHug(), and receivePinch() are depend upon state of object and they are non static Method.
Now Comple and run same class by making receiveHug(), and receivePinch() method Static .
public class MrHappyObject {
private final static String _HAPPY = "happy";
private static String _mood = _HAPPY;
private final static String _ANNOYED = "annoyed";
private final static String _ANGRY = "angry";
private static int _instantiations;
public static void main( String [] args ) {
MrHappyObject obj1 = new MrHappyObject();
MrHappyObject obj2 = new MrHappyObject();
obj1.printMood();
obj2.printMood();
obj1.receiveHug();
obj2.receivePinch();
obj1.printMood();
obj2.printMood();
}
public void printMood() {
System.out.println( "I am " + _mood );
}
public static void receivePinch() {
if( _mood.equals( _HAPPY ) ) {
_mood = _ANNOYED;
} else {
_mood = _ANGRY;
}
}
public static void receiveHug() {
if( _mood.equals( _ANGRY ) ) {
_mood = _ANNOYED;
} else {
_mood = _HAPPY;
}
}
public MrHappyObject() {
_instantiations++;
}
public static int instances() {
return _instantiations;
}
}
And the output is
I am happy
I am happy
I am annoyed
I am annoyed
This is not our desired result.
Now this makes clear when to use Static method and when to use non static method.
How to create OTA server?
For creating OTA server you need HTTP server (Web server i.e tomcat50-jwsdp).
Now create new folder under web apps like C:\tomcat50-jwsdp\webapps\counter
Counter contains 2 folder ==>WEB-INF (it contains web.xml), images (or any other name ,it contains JAD n JAR)
Put MIME Type of JAD and JAR.
jad
text/vnd.sun.j2me.app-descriptor
jar
application/java-archive
And access this jad file from your mobile browser it will automatically invoke AMS.
Or can see it from your PC browser
http://localhost:8080/counter/images/
As images folder contains JAD and JAR file. Change locathost to your actual address.
Write Hindi font in mobile
And then read it using :
StringBuffer sb = new StringBuffer();
public void readMe(){
InputStream is = null;
try
{
is = getClass().getResourceAsStream("/name.utx");
Reader r = new InputStreamReader(is, "UTF-8");
int c = 0;
while (true) {
c = r.read();
if (c == -1) {
break;
}
sb.append( (char) c);
}
}
catch (Exception i)
{
System.out.println("Error in Read ME ");
}
}
Some IMP Link for Device Properties
http://www.jbenchmark.com/index.jsp
http://www.club-java.com/TastePhone/J2ME/MIDP_mobile.jsp
http://developers.samsungmobile.com/Developer/index.jsp
http://www.forum.nokia.com/devices/matrix_all_1.html
http://developer.sonyericsson.com/site/global/docstools/phonespecs/p_phonespecs.jsp
http://developer.motorola.com/products/handsets/
http://www.gsmarena.com/
http://www.mobref.com/home/
-----------------------------------------------------------------------------------------------
