Thursday, April 7, 2011

Send SMS in Blackberry using J2ME

Hello,

When i had to implement this feature then i surfed a lot.I was new to Blackberry and J2ME.
I saw several posts but non was able to help me truely.

I gathered up the code and made it to work.
I had to send the message to the person whose call i missed up or to person whose incomming call is explicitly disconnected by me when i was busy.

The moment i disconnect the call, immediately a message is send to thta number.
That too should be done in a separate thread to avoid hang ups.

Hope it help someone. :)


Send SMS from Blackberry Application:

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

import net.rim.device.api.system.RadioInfo;
public class SendSMS extends Thread {
    private String to;
    private String msg;

    public SendSMS(String to, String msg) {
        this.to = to;
        this.msg = msg;

    }
    public void run() {
        if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
            DatagramConnection dc = null;
            try {
                dc = (DatagramConnection) Connector.open("sms://" + to);
                byte[] data = msg.getBytes();
                Datagram dg = dc.newDatagram(dc.getMaximumLength());
                dg.setData(data, 0, data.length);
                dc.send(dg);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    dc.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }

        } else {
            MessageConnection mc = null;
            try {
                mc = (MessageConnection) Connector
                        .open("sms://" + to);
                TextMessage m = (TextMessage) mc
                        .newMessage(MessageConnection.TEXT_MESSAGE);
                m.setPayloadText(msg);
                mc.send(m);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                try {
                    mc.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());

                }
            }
        }
    }

}

Send msg when call gets disconnected:
public void callDisconnected(int callId)
{
        final PhoneCall call = Phone.getCall(callId);
        final String number = call.getDisplayPhoneNumber();
        SendSMS sendSMS = new SendSMS(number, "message");
        sendSMS.start();
        super.callDisconnected(callId);
    }
You can try other methods also depending upon the requirements.


Links:
http://stackoverflow.com/questions/3051301/send-sms-from-background-thread-in-blackberry-using-j2me

Tuesday, April 5, 2011

Sending Email with Attachment in Blackberry using J2ME


Now days in almost every application user has to send email and share the contents such as score of any game etc..
Using the below code in any blackberry application one can easily do that.


Address[] address = new Address[1];
try

  {
    address[0] = new Address(email,name);
  }

   catch (AddressException e1)
    {
      e1.printStackTrace();
    }
 byte[] data = readFile();
 Multipart multipart = new Multipart();
 SupportedAttachmentPart attach ;

 attach = new SupportedAttachmentPart(multipart,"application/x-example", "test.txt", data);
 multipart.addBodyPart(attach);
 Message msg = new Message();

// add the recipient list to the message
 try

  {
     msg.addRecipients(Message.RecipientType.TO, address);

    // set a subject for the message
   msg.setSubject("Mail from mobile");
   msg.setContent(multipart);
  }

  catch (MessagingException e1)
   {
      e1.printStackTrace();
   }


try

 {
     Transport.send(msg);
 }

 catch (MessagingException e) {
    System.out.println(e.getMessage());
  }
 private static byte[] readFile() {
 String fName ="
file:///store/home/user/test.txt";
 byte[] data = null;
 FileConnection fconn = null;
 DataInputStream is = null;
 try

  {
      fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
      is = fconn.openDataInputStream();
     data = IOUtilities.streamToBytes(is);
   }

  catch (IOException e)
   {
      System.out.println(e.getMessage());
   }

  finally
  {
     try

     {
        if (null != is)
        is.close();
        if (null != fconn)
       fconn.close();
     }

   catch (IOException e)
     {
             System.out.println(e.getMessage());
      }
  }
 return data;
 }


Have a look at this sample image:

Custom Popups in Blackberry



Procedure:

1) Create a class that extends Popup .
2) In this class use your own manager
a) take one vertical field manager
b) add some text using label field and also a button inside this vertica field manager
c) And add vertical field manager in your screen


PopupScreen popup = new PopupScreen(new VerticalFieldManager());
popup.add(new LabelField("Hello!"));
popup.add(new ButtonField("OK"));



Create Border less Popup screen
PopupScreen popup = new PopupScreen(new VerticalFieldManager());
popup.add(new LabelField("Hello!"));
Border border = BorderFactory.createSimpleBorder(new XYEdges(), Border.STYLE_TRANSPARENT);
popup.setBorder(border);



Push popup screen:

UiApplication.getUiApplication().pushScreen(new MyPopup());

Closing a popup scren when uer clicks on Escape Key:
Need to implement Keychar method

popupscreen1=new PopupScreen(myverticalfieldmanager)
   {
        protected boolean keyChar(char c, int status, int time)
          {
               if (c == Characters.ESCAPE)
              close();
              return super.keyChar(c, status, time);
         }
   };



Have a look at this:

Monday, January 17, 2011

Using image for a TextEditField in Blackberry

Hello all,
 
When i started coding for basic edit field in blackberry i found 
that it is transparent but the look was not exactly that i wanted. 
I wanted a look of TextEditField that appears in websites 
so i tried the below mentioned code. 
May be it can help to any blackberry developer.
 
Here is the code:
 
LabelField label = new LabelField("name");

textbox=new EditField("","",500, 
 EditField.NO_NEWLINE|Field.FOCUSABLE) 
 {
  protected void paint(Graphics g)
   {
     g.setColor(Color.MAROON);
     super.paint(g);
   }
  protected boolean keyChar(char key, int status, int time) 
   {
     return super.keyChar(key, status, time);
   }
 };


 manager = new VerticalFieldManager(HORIZONTAL_SCROLL )
  {
    protected void paint(Graphics g) 
     {
      int x = this.getHorizontalScroll();
      if(textbox.getText().equals(""))
      {
        g.drawBitmap( x, 0, textbox_img.getWidth(), 
           textbox_img.getHeight(),textbox_img, 0, 0 );
      }
     super.paint(g);
   }
}
manager.add(textbox);
 
add(label);
add(manager); 
 
now add this manager in your main screen and see how it looks.
Its even supports horizontal scroll.
  
Look at this:
 
 
  
  
  
 
 
 

Wednesday, January 12, 2011

Adding Menu Items in existing Blackberry Apps

Hello every one,

Sometimes it happens that you want to add your own menu item to the existing blackberry applications.When user clicks menu key in an existing application then a menu item added by you is visible say "Open with myApp" or "import with myApp".

This can be achieved using the ApplicationMenuItemRepository class.
net.rim.blackberry.api.menuitem package, enables you to add menu items to BlackBerry applications.

Features:
1) It enables you to add or remove application menu items.
2) It provides constants that define the contexts in which a menu items can appear.

For example:
The ApplicationMenuItemRepository.MENUITEM_CALENDAR constant specifies that the menu item appears when the calander is open.

In this sample we will invoke calander application by clicking on a button and we can see a new menu item added on the calendar app.

Here you go:

package com.Test;

import java.util.Date;
import javax.microedition.pim.Event;
import net.rim.blackberry.api.invoke.CalendarArguments;
import net.rim.blackberry.api.invoke.Invoke;
import net.rim.blackberry.api.menuitem.ApplicationMenuItem;
import net.rim.blackberry.api.menuitem.ApplicationMenuItemRepository;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

public class ApplicationMenuDemo extends MainScreen
{
    LabelField lbl;
    ApplicationMenuDemo()
    {
        super();
       
        MyMenuItem myMenuitem = new MyMenuItem(0);
        ApplicationMenuItemRepository.getInstance().addMenuItem(
        ApplicationMenuItemRepository.MENUITEM_CALENDAR, myMenuitem);
       
        setTitle("ApplicationMenuItemRepository Demo");
       
        lbl = new LabelField("imported start date will be displayed here");
       
        ButtonField btn = new ButtonField("import from Calendar");
        btn.setChangeListener(listener);
       
        add(new LabelField("",LabelField.NON_FOCUSABLE));
        add(lbl);
        add(new LabelField("",LabelField.NON_FOCUSABLE));
        add(btn);
    }
   
    FieldChangeListener listener = new FieldChangeListener()
    {
        public void fieldChanged(Field field, int context)
        {
          Invoke.invokeApplication(Invoke.APP_TYPE_CALENDAR, new
                 CalendarArguments(CalendarArguments.ARG_VIEW_DEFAULT));
        }
    };
   
     class MyMenuItem extends ApplicationMenuItem
        {
            String text;
            MyMenuItem(int order)
            {
                super(order);
            }

            public Object run(Object context)
            {
                if (context instanceof Event)
                {
                    Event event = (Event) context;
                   
                    Date date = new Date((event.getDate(Event.START, 0)));
                                       
                    lbl.setText(date.toString());
                }
                return context;
            }

            public String toString()
            {
                return "Import Calander Date";
            }
        }
}
See how it looks:

 

 




link for api details:

http://www.blackberry.com/developers/docs/4.0.2api/index.html
Enjoy coding :)

Tuesday, January 11, 2011

Ads Service in Blackberry

Hello

Working with Ads Service in Blackberry is really great and new experience for those who haven't worked on iAds in iPhone.
I have gathered some information that i would like to share with all and may be some where somebody can be helped by it.

Advertisements rule the world...Keeping this in mind Blackberry platform provides you the capability to display ads in your Blackberry Device Application. Many of you must have seen such feature in iPhone Apps where ads are called as iAds.

To sign up for the Advertising Service, visit adservice.blackberry.com/register/




Using the Advertising Service SDK:

1) For each application that you integrate ads into, you need a unique instance of the Advertising Service SDK.

2) If you have multiple applications in which you want to display ads, you must register each application with Research In Motion separately.

3) Each application that you register, RIM sends you a new SDK which is identified by a unique package ID.

4) To use the Advertising Service API in an application, you have to add the .jar file for the Advertising Service API to the build path of a BlackBerry application project,after this develop and package the application, and distribute the application .cod file with the .cod file that contains the Advertising Service API.

System requirements

• BlackBerry® Java® Plug-in for Eclipse® 1.1 or later with the BlackBerry Java SDK 4.5 - 5.0.
"The Advertising Service does not yet fully support BlackBerry® Device Software 6.0."

• BlackBerry® Java® Development Environment 4.5 or later

• BlackBerry® Email and MDS Services Simulator Package 4.1.2 or later


How to move ahead:

1) RIM send you two zipped files that you need to unzip

BlackBerrySDK_app<package_ID>._Desktop

BlackBerrySDK_app<package_ID>._OTA

2) When you unzip them you can find many folders that contains the alx, cod, jad, jar files for different versions.

Files contained:
net_rim_bbapi_adv_<package_ID>.alx

net_rim_bbapi_adv_<package_ID>.cod

net_rim_bbapi_adv_<package_ID>.jad

net_rim_bbapi_adv_<package_ID>.jar


3) To add the .jar file of the Advertising Service API to your BlackBerry application Project :

Create a BlackBerry application project:

1. In Eclipse, in the Package/Project Explorer view, right-click the project that you want to add the .jar file to.
2. Click Build Path > Configure Build Path.
3. Click the Libraries tab.
4. Click Add External JARS if the .jar file is not in the current workspace (Prefer to add the jar file of particular version in your src folder).
5. Double-click net_rim_bbapi_adv_<package_ID>.jar to add the .jar file to the project.
7. Click OK.

Note: This itself doesn’t completes the task, you must also load the .cod file for the Advertising Service API on a BlackBerry device or in the BlackBerry Smartphone Simulator before an application can run.It would be a better option if you place the cod file in the simulators directory.

Ads Display Size
The Advertising Service supports the following sizes of ads, in pixels:
• 320 x 53 (required size for rich media ads)
• 216 x 36
• 168 x 28
• 120 x 20

Namespace:

import net.rim.blackberry.api.advertising.<package_ID>.Banner;

Here you go

package com.Test;

import net.rim.blackberry.api.advertising.appXXXXX.Banner;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
class Ads extends UiApplication
{
    public static void main(String[] args)
     { 
       Ads theApp = new Ads();
       theApp.enterEventDispatcher();
     }
    public Ads()
     {
        pushScreen(new AdDemoScreen());
     }

 class AdDemoScreen extends MainScreen
   {
      public AdDemoScreen()
       {
          Banner bannerAd = new Banner(placementId, null);
          bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_LARGE);
         add(bannerAd);
       }
   }
 }

How to send Meta data with Ads:

import net.rim.blackberry.api.advertising.<package_ID>.Banner;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
import java.util.Hashtable;

  public class Ads extends UiApplication
   {
      public static void main(String[] args)
       {
         Ads theApp = new AdDemo();
         theApp.enterEventDispatcher();
       }
    public Ads()
    {
       pushScreen(new AdsScreen());
     }
  }
 class AdsScreen extends MainScreen
  {
     public AdsScreen()
     {
        Hashtable metadata = new Hashtable();
        metadata.put("age", "61");
        metadata.put("gender", "female");

        Banner bannerAd = new Banner(placement_Id, metadata);
        bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_LARGE);
        add(bannerAd);
     }
 }

package_ID : (appXXXXX) You can see this number on the files that RIM send you.(net_rim_bbapi_adv_appXXXXX.jar).

placement_Id : When RIM sends you the files they also send some credentials containing placement_id

Package a BlackBerry application project
1. In Package Explorer view, right-click a BlackBerry project.
2. Click BlackBerry > Package Project(s).
The Console view displays the progress of packaging.


Run an application that displays ads on a device
1. Connect a BlackBerry device to a computer with a USB cable.
2. Oopen Command prompt.
3. At the command prompt, type cd <location_of_application_deliverable_files> and press Enter.
4. At the command prompt, type javaloader -u load <my_jad_file.jad> and press Enter to load the .jad file for the application on the BlackBerry device.
6. On the Home screen of the device, navigate to and click the application icon.

Customizing the appearance and behavior of the display area for an ad

1) setMMASize() : Sets the size of the Banner object.

1) If your application runs on a BlackBerry Device Software version earlier
than 5.0 so use setMMASize().

2) If your application runs on BlackBerry Device Software 5.0, and you do not set the size in the application code, the Banner object resizes itself automatically to match the size of the ad that the mediation layer returns.

If you set a size that is different from the one that you specify when you register your application, the server-side value overrides the size that you set in the application, potentially causing ads to display incorrectly.


bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_LARGE);
Other Options for size:

Banner.MMA_SIZE_EXTRA_SMALL

Banner.MMA_SIZE_EXTRA_MEDIUM

Banner.MMA_SIZE_EXTRA_LARGE

Banner.MMA_SIZE_EXTRA_AUTO


2) Transition effect - The application by default displays a black transition effect between 2 ads.You can call this as fade in and fade out.

bannerAd.enableBannerTransition(false) – To turn off the transition effect
bannerAd. setBannerTransitionColor(Color.RED) - To specify a transition color that is supported by the Color class in the BlackBerry® Java® SDK.


3) Focus behavior- The application by default displays a blue border around the ad By default, when a user selects an ad.

bannerAd setBorderColor(Color.BLACK) - To specify a focus color that is supported by the Color class in the BlackBerry® Java® SDK.

bannerAd.setFocusOverrideFlag(true) – To prevent the Advertising Service API from handling focus behavior.


4) Placeholder image - Tthe application by default displays a transparent placeholder image with a border when ad service is waiting for an ad. You can customize the placeholder image, you can create a Bitmap object and pass it to the constructor for a Banner object as a parameter.

If you create your own placeholder image, verify that it has the same dimensions as the ads that
your application receives.

Bitmap customPlaceholder = Bitmap.getBitmapResource("Ad_placeholder.png");

Banner bannerAd = new Banner(placementId, null, 100000, customPlaceholder);

Enjoy Coding!!!!!!!!!!!

:)

How to create a Custom Button Field in Blackberry

Hello all,
This is my first blog.I will be happy if it can help blackberry developers in any way.

Custom Buttons :  Blackberry supports buttons that a very simple yet use full which is by default dark grey in color and when it gets focus then it appears in blue color.

Most of the time we want to create apps or projects with a wide variety of graphics in it that can appeal the user.

For this purpose we can create our own custom buttons and apply focusable and non focusable images on it.Moreover we can also add text to it.

Here u go:

package com.MyProject;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;

public class CustomButtonField extends Field
{
    Bitmap Unfocus_img, Focus_img, current_pic;
    int width;
    String text;
    Font font;   
    CustomButtonField(int width, String text, Bitmap onFocus, Bitmap onUnfocus, long style)
    {
        super(style);
        Unfocus_img = onUnfocus;
        Focus_img = onFocus;
        current_pic = onFocus;
        this.text = text;
        this.width = width;
    }
    protected void layout(int width, int height)
    {
        setExtent(current_pic.getWidth(), current_pic.getHeight());       
    }
    protected void paint(Graphics graphics)
    {
        try
        {
                FontFamily fntFamily = FontFamily.forName("BBAlpha Sans");
                font = fntFamily.getFont(Font.BOLD,14);             
        }
        catch(Exception e)
        {
            font = Font.getDefault();
         
        }
        graphics.setFont(font);
        graphics.setColor(Color.WHITE);
        graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic, 0, 0);
        graphics.drawText(text, width, 7);
    }
    protected void onFocus(int direction)
    {
        super.onFocus(direction);
        current_pic = Unfocus_img;
        this.invalidate();
    }
  protected void drawFocus(Graphics graphics, boolean on)
  {
       
    }
    protected void onUnfocus()
    {
        super.onUnfocus();
        current_pic = Focus_img;
        invalidate();
    }
    public boolean isFocusable() {
        return true;
    }
    protected boolean navigationClick(int status, int time) {
        fieldChangeNotify(0);
        return true;
    }
}


And this is how u can use it:
Bitmap focus = Bitmap.getBitmapResource("printButton_focus.png");
Bitmap unfocus = Bitmap.getBitmapResource("printButton_unfocus.png");
           
Bitmap focus1 = Bitmap.getBitmapResource("button-highlight.png");Bitmap unfocus1 = Bitmap.getBitmapResource("button.png");
           
 ButtonField obj = new ButtonField("Button");
 CustomButtonField button1 = new CustomButtonField(0,"",unfocus,focus,Field.FOCUSABLE);
 CustomButtonField button2 = new CustomButtonField(25,"Next",unfocus1,focus1,Field.FOCUSABLE);
           
 add(obj);
 add(new RichTextField(Field.NON_FOCUSABLE));
 add(button1);
 add(new RichTextField(Field.NON_FOCUSABLE));
 add(button2);


Result of three added buttons depending upon the argument
Unfocus  

Focus    

Unfocus 
   
Focus    

Unfocus

Focus   


Thank you to all those who helped me!!!!