IT Community - Software Programming, Web Development and Technical Support

j2me programing with BlackBerry phones -useful tips

This is a discussion on j2me programing with BlackBerry phones -useful tips within the Blackberry forums, part of the Mobile Software Development category; How To - Play audio in an application The Mobile Media application programming interface (API), known as Java Specification Request (JSR) ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > Mobile Software Development > Blackberry

Register FAQ Members List Calendar Mark Forums Read
  1 links from elsewhere to this Post. Click to view. #1 (permalink)  
Old 10-27-2007, 12:22 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

How To - Play audio in an application

The Mobile Media application programming interface (API), known as Java Specification Request (JSR) 135, provides a specification for playing audio on BlackBerry devices. The example below shows how to use this API to play an MP3 audio file in an application.

Note: The classes involved can be found in the javax.microedition.media package.

//first we need to find the supported content types
String types[] = Manager.getSupportedContentTypes(null);
for (int cnt = types.length - 1; cnt >= 0; --cnt) {
if (types[cnt].equals("audio/mpeg")) {
//this sample demonstrates playing an MP3 file that has been
//added as a resource to the project
try {
//retrieve the MP3 file
Class clazz = Class.forName("com.rim.samples.AudioDemo");
InputStream is = clazz.getResourceAsStream("/TarzanYell.mp3");
//create an instance of the player from the InputStream
Player player = javax.microedition.media.Manager.createPlayer
(is, "audio/mpeg");
player.realize();
player.prefetch();
//start the player
player.start();
} catch (Exception ex) { }
} else if (types[cnt].equals("audio/x-wav ")) {
//this is where you would play wav files
} else if (types[cnt].equals("audio/midi ")) {
//this is where you would play midi files
}

}

Alternatively, you can play audio by launching the BlackBerry device media application. To do so invoke the BlackBerry® Browser with a URL that points to your audio content. The URL could point to a web server or to a file located on the microSD card of the BlackBerry device (i.e.: "file:///SDCard/yourDirectory/yourFile.mp3" .
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 10-27-2007, 12:39 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

Record Audio on a BlackBerry smartphone

BlackBerry Device Software 4.2 implemented Java Specification Request (JSR) 135 Mobile Media API (MMAPI). This allows BlackBerry smartphone applications to record and play back multimedia content.

The BlackBerry smartphone supports audio recording using two different formats, Adaptive Multi-Rate (AMR) and 8khz mono-16-bit Pulse Code Modulation (PCM). The default encoding used by the BlackBerry smartphone is AMR. The encoding to be used is specified in the String passed to the Manager.createPlayer(String locator) method. The following table shows a list of supported locator strings.



The following code sample demonstrates how to record audio using JSR 135 on a BlackBerry smartphone. The sample encapsulates this in a thread that can be added to your application.

Code:
final class VoiceNotesRecorderThread extends Thread
{
   private Player _player;
   private RecordControl _rcontrol;
   private ByteArrayOutputStream _output;
   private byte _data[];

   VoiceNotesRecorderThread() {}

   private int getSize()
   {
       return (_output != null ? _output.size() : 0);
   }

   private byte[] getVoiceNote()
   {
      return _data;
   }

   public void run() {
      try {
          // Create a Player that captures live audio.
          _player = Manager.createPlayer("capture://audio");
          _player.realize();

          // Get the RecordControl, set the record stream,
          _rcontrol = (RecordControl)_player.getControl("RecordControl");

          //Create a ByteArrayOutputStream to capture the audio stream.
          _output = new ByteArrayOutputStream();
          _rcontrol.setRecordStream(_output);
          _rcontrol.startRecord();
          _player.start();

      } catch (final Exception e) {
         UiApplication.getUiApplication().invokeAndWait(new Runnable() {
            public void run() {
               Dialog.inform(e.toString());
            }
         });
      }
   }

   public void stop() {
      try {
           //Stop recording, capture data from the OutputStream,
           //close the OutputStream and player.
           _rcontrol.commit();
           _data = _output.toByteArray();
           _output.close();
           _player.close();

      } catch (Exception e) {
         synchronized (UiApplication.getEventLock()) {
            Dialog.inform(e.toString());
         }
      }
   }
}
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 10-27-2007, 12:41 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow Re: j2me programing with BlackBerry phones -useful tips

How To - Specify Audio Path Routing

The AudioPathControl interface in the BlackBerry smartphone application programming interface (API) set allows an application to specify the route that is used to play back or record audio. This means your application could play back and/or record audio using a specified speaker and microphone. For example, you can specify the speaker and microphone built into the BlackBerry smartphone, a Bluetooth® headset, or a wired headset.

The following portion of code shows how to route audio to a Bluetooth headset:

Code:
try {
      Player p =
javax.microedition.media.Manager.createPlayer("http://mycompany/test.mp3");
      p.realize();
      p.prefetch();
      Control[] c = p.getControls();
      for(int i=c.length-1; i>=0; --i) {
          if(c[i] instanceof AudioPathControl) {
                AudioPathControl apc = (AudioPathControl)c[i];

                try{
                   //Route the audio to Bluetooth. For more
                   audio path options see the AudioPathControl                    javadocs.
                    apc.setAudioPath(AudioPathControl.AUDIO_PATH_BLUETOOTH);
                   } catch(Exception e) {
                     System.err.println(e.toString()); }
          }
      }
      p.start();
}
catch(Exception e) { System.err.println(e.toString());
}
__________________
thanx n regards
jeyaprakash.c

Last edited by jeyaprakash.c : 10-27-2007 at 12:48 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 10-27-2007, 12:46 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

How To - Support streaming audio to the media application

The media application on the BlackBerry device is designed to read from the local file system. To stream data from a remote resource to the media application, you must buffer the resource and control the media application's data reads. The best method to accomplish this is to create a custom DataSource and SourceStream implementation that will provide data to the media application.
Buffering data

The following example opens a connection to a remote audio file and buffers an initial amount of data before starting playback. Subsequent read requests from the media application are controlled by limiting the amount of data returned and blocking the read request when the amount of available data is low. When enough data is available, the read request is resumed.

The example also includes support for saving a downloaded audio file to a microSD card and playing back a downloaded file from the microSD card.

Buffering in the SourceStream is done using SharedInputStreams. One thread reads from a connection to the resource, tracking how much data has been read into the stream. The following code shows this thread:

Code:
private class ConnectionThread extends Thread {
    public void run() {
        try {
            byte[] data = new byte[READ_CHUNK];
            int len = 0;
            updateLoadStatus(_resources.getString(BufferedPlaybackResource.LOAD_BUFFERING));
            while (-1 != (len = readAhead.read(data))) {
                totalRead += len;
                updateLoadStatus(totalRead + _resources.getString(BufferedPlaybackResource.LOAD_UNITS));
                if (!bufferingComplete && totalRead > getStartBuffer()) {
                    bufferingComplete = true;
                    System.out.println("Initial Buffering Complete");
                    updateLoadStatus(_resources.getString(BufferedPlaybackResource.LOAD_BUFFER_COMPLETE));
                }
                if (_stop) {
                    return;
                }
            }
            System.out.println("Downloading Complete");
             updateLoadStatus(_resources.getString(BufferedPlaybackResource.LOAD_DONE) + totalRead + _resources.getString(BufferedPlaybackResource.LOAD_UNITS));
            System.out.println("Total Read: " + totalRead);
            if (totalRead != s.getLength()) {
                 System.err.println("* Unable to Download entire file *");
            }
            downloadComplete = true;
            // Write download to the local file
            readAhead.setCurrentPosition(0);
            while (-1 != (len = readAhead.read(data))) {
                saveStream.write(data);
            }
         } catch (Exception e) {
             System.err.println(e.toString());
          }
    }
}
Notice that the application waits until the whole file has been downloaded before saving it to local storage. Writing to storage while downloading the file may slow down the download process. After reading the data, the thread makes the data available to the SharedInputStream.
Reading data

Read requests from the media application are handled by the SourceStream provided by the DataSource. Internally, this SourceStream implementation uses a SharedInputStream based on the stream being read by the thread in the prior example.

The available() method of the SharedInputStream determines how far ahead the stream has been read. When the media application has caught up to the download, the application can block further read requests from the media application until the download is far enough ahead. The goal is to support playback as soon as possible and not stop unless necessary. If stopping is required, try to minimize it by stopping long enough to buffer additional data for playback.

There are four parameters used in the DataSource to define the buffering scheme:

1. Initial buffer - the amount downloaded before playback starts
2. Pause mark - defines when reading should be blocked because too little data is available
3. Restart mark - defines when reading should be allowed again
4. Limit - defines the amount of data returned at a time

The following example allows these settings to be manually adjusted, while in practice they could be set to correspond to the audio being streamed, and/or automatically adjusted to match network conditions.

The following example shows the read method of the StreamingSource implementation:

Code:
public int read(byte[] b, int off, int len) throws IOException {
    System.out.println("Read Request for: " + len + " bytes");
    // limit bytes read to our readLimit.
    int readLength = len;
    if (readLength > getReadLimit()) {
        readLength = getReadLimit();
    }
    int available;
    boolean restart_pause = false;
    for (;; ) {
        available = _baseSharedStream.available();
        if (downloadComplete) {
          // Ignore all restrictions if downloading is complete
          System.out.println("Complete, Reading: " + len + " - Available: " + available);
          return _baseSharedStream.read(b, off, len);
        } else if (bufferingComplete) {
         if (restart_pause && available > getRestartBytes()) {
                // start up again
                System.out.println("Restarting - Available: " + available);
                updatePlayStatus(_resources.getString(BufferedPlaybackResource.PLAY_RESTART) + available + _resources.getString(BufferedPlaybackResource.LOAD_UNITS));
                restart_pause = false;
                return _baseSharedStream.read(b, off, readLength);
         } else if (!restart_pause && (available > getPauseBytes() || available > readLength)) {
             // we have what is needed
             if (available < getPauseBytes()) {
                 // read this time, but set the pause
                 restart_pause = true;
                 updatePlayStatus(_resources.getString(BufferedPlaybackResource.PLAY_PAUSING) + available + _resources.getString(BufferedPlaybackResource.LOAD_UNITS));
             }
             System.out.println("Reading: " + readLength + " - Available: " + available);
             return _baseSharedStream.read(b, off, readLength);
           } else if (!restart_pause) {
               // Set pause until loaded enough to restart
               restart_pause = true;
                updatePlayStatus(_resources.getString(BufferedPlaybackResource.PLAY_PAUSING) + available + _resources.getString(BufferedPlaybackResource.LOAD_UNITS));
             }
          } else {
              try {
                  Thread.sleep(100);
              } catch (Exception e) {
                  System.err.println(e.getMessage());
                }
            }
      }
}
The DataSource determines where the data is loaded from during the connect() method. It first opens a connection to the remote resource to get the filename and length and then opens a connection to the local file system. If a file of the same name doesn't exist, or is smaller than the remote file, it is replaced by downloading the file again. Otherwise, the local resource is passed as the resource stream to be read. The details are as follows:

Code:
public void connect() throws IOException {
    System.out.println("Loading: " + getLocator());
    s = (ContentConnection) Connector.open(getLocator(), Connector.READ);
    System.out.println("Size: " + s.getLength());
    // Open save file location
    int filenameStart = getLocator().lastIndexOf('/');
    int paramStart = getLocator().indexOf(';');
    if (paramStart < 0) {
        paramStart = getLocator().length();
    }
    String filename = getLocator().substring(filenameStart, paramStart);
    System.out.println("Filename: " + filename);
    saveFile = (FileConnection) Connector.open("file:///SDCard/blackberry/music" + filename, Connector.READ_WRITE);
    if (!saveFile.exists()) {
        saveFile.create();
    }
    saveFile.setReadable(true);
    SharedInputStream fileStream = SharedInputStream.getSharedInputStream(saveFile.openInputStream());
    fileStream.setCurrentPosition(0);
    if (saveFile.fileSize() < s.getLength()) {
        // didn't get it all before, download again
        saveFile.setWritable(true);
        saveStream = saveFile.openOutputStream();
        readAhead = SharedInputStream.getSharedInputStream(s.openInputStream());
    } else {
        downloadComplete = true;
        readAhead = fileStream;
        s.close();
      }
      if (forcedContentType != null) {
          feedToPlayer = new LimitedRateSourceStream(readAhead, forcedContentType);
      } else {
          feedToPlayer = new LimitedRateSourceStream(readAhead, s.getType());
        }
}
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 10-27-2007, 12:52 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

Known Issue - Delay in playing audio when streaming to a Bluetooth headset

Background

Audio path routing allows an application to redirect audio to supported output components (e.g. speakers, wired headset, Bluetooth® headset) that are used with the BlackBerry smartphone. An application can leverage this functionality using the AudioPathControl class. See DB-00575 for an example of how to use the AudioPathControl class.
Problem

A delay occurs in the audio file that is being played when streaming it to a Bluetooth headset. (e.g. the first one or two words of the file are cut off).
Workaround

Insert three seconds of blank audio to the beginning of the audio file.

This is a previously reported issue that has been escalated internally to our development team. No resolution time frame is currently available.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 10-27-2007, 12:55 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

Alert.startBuzzer() does not work

Problem

Alert.startBuzzer() and Alert.setBuzzerVolume() are not supported by the BlackBerry 7100 Series device and later devices.

The BlackBerry 7100 Series device and later devices contain a hardware upgrade that changes the way audio is produced.
Resolution

As an alternative to Alert.startBuzzer(), we recommend Alert.startMIDI(). To determine the method to use, the following tests are performed:

if( Alert.isBuzzerSupported() )
{
Alert.startBuzzer(…);
} else if( Alert.isMIDISupported() )
{
Alert.startMIDI(…);
}

Note: If you use a polyphonic tone, use the above test to check the availability of Alert.startADPCM(). You can do so via Alert.isADPCMSupported().
__________________
thanx n regards
jeyaprakash.c

Last edited by jeyaprakash.c : 11-01-2007 at 07:20 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 10-27-2007, 12:56 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

Playing audio in an application pauses the Media application on BlackBerry smartphones operating on CDMA networks

Problem

For BlackBerry smartphones that operate on CDMA networks, when an application attempts to play an audio stream while the Media application is playing, the Media application will stop.
Cause

BlackBerry smartphones that operate on CDMA networks are limited to a single audio stream, while BlackBerry smartphones that operate on Global System for Mobile Communications® (GSM®) networks can handle two concurrent audio streams.

BlackBerry smartphones that operate on CDMA networks handle multiple audio streams by giving precedence to the last started audio stream.
Resolution

You can program your application to register a PlayerListener to monitor playback. When another Player supersedes playback, a Stop event will be received.

Note: No notification is sent when the other playback is complete.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 10-27-2007, 01:02 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Default Re: j2me programing with BlackBerry phones -useful tips

Media application error codes
When monitoring media application events using a PlayerListener, the playerUpdate() method can receive an error event and an integer for the eventData. These integers are range from 1 to 6 and have the following meanings:

__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 10-27-2007, 01:04 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

setMediaTime does not work for AMR files

When using the Player method to seek the media time in an Adaptive Multi-Rate (AMR) encoded file, seeking past the first 58 KB of the file does not work. Seeking is possible within the first 58 KB of the AMR file, provided the file size is known, and setMediaTime is called after the PlayerListener.STARTED event is received.

To work around this limitation, implement and call a custom DataSource method to handle the seeking separately.

The SourceStream implementation should contain a special operation to handle the AMR seeking. The following is an example for 12.2kbps AMR files, which is the encoding standard used for files recorded on the BlackBerry device. AMR files are broken into 20 millisecond frames, and 12.2kbps files have 32bytes per frame. Each AMR file also has a 6 byte header.

Code:
public void amrSeek(long millis) {
        int frame = (int) millis/20;
        readLocation = (framenumber * 32) + 6;
}
The SourceStream read method should use the readLocation variable to define where reads to the media stream will start because it is the beginning of the frame that has been seeked.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 10-27-2007, 01:09 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow Re: j2me programing with BlackBerry phones -useful tips

What Is - Supported audio formats

The supported audio formats for BlackBerry smartphones are summarized in the following table:



Additional Information

AAC (Advanced Audio Coding) - The supported formats include MPEG2 and MPEG4, as well as HE-AAC / AAC+. The supported sample rates are 8 KBps, 11.025 KBps, 12 KBps, 16 KBps, 22.05 KBps, 32 KBps, 44.1 KBps and 48 KBps. The supported channels are all configurations of mono and stereo (Note: Depending on the BlackBerry Device Software version, AAC+ may not support parametric stereo ).

ADPCM2 - This is a proprietary sampled audio format.

AMR (Adaptive Multi-Rate) - The supported AMR-NB rates are 4.75 KBps, 5.15 KBps, 5.9 KBps, 6.7 KBps, 7.4 KBps, 7.95 KBps, 10.2 KBps, and 12.2 KBps; and the input must conform to RFC3267 Section 5 on the Internet FAQ Archive web site.

AU
- This is a simple audio file format and associated with the µ-law logarithmic encoding.

GSM® (Global System for Mobile Communications®)
- The supported sample rates range from 5.6 KBps to 13.2 KBps with a sampling rate of 8 kHz.

MIDI
- Partial support of MIDI on earlier BlackBerry smartphone models refers to a buzzer capable of buzzing at various frequencies and volumes. All other BlackBerry smartphone models support polyphonic MIDI22.

MIDP-TS (Mobile Information Device Profile 2.0 Tone Sequence) - Provides mobile devices with the capability to create simple monophonic tone sequences based on MIDP 2.0.

MP3
- The supported format is MPEG-1 Layer 3; the supported sample rates are 32KHz, 44.1KHz, and 48KHz; and the supported channels are 1 (mono) and 2 (stereo).

WAV
- The supported encodings include PCM, uLaw, and aLaw. The supported sampling rates are 8 kHz, 16 kHz, 22.05 kHz, 32 kHz, 44.1 kHz, and 48 kHz with 8-bit and 16-bit depths in mono or stereo.

Windows Media Audio (WMA)
- WMA 9 standard profile decoder and WMA 10 professional profile decoder are supported by BlackBerry smartphones running BlackBerry Device Software 2.2.1 or later2. The WMA 9 standard profile decoder provides six channels at 128 KBps, starting at 96 kHz/24-bit. The WMA 10 professional profile decoder provides 8 channels decoding at 128 KBps.

1 Supports MP4

2 The supported MP3 formats for BlackBerry smartphones are MPEG Part 1 and Part 2 audio layer 3; the supported sample rates are 16kHz, 22.050kHz, 24kHz, 32kHz, 44.1kHz, and 48kHz.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 10-27-2007, 01:14 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

How To - Add a custom menu item to an existing BlackBerry application

Procedure

The ApplicationMenuItem class will allow the addition of a custom menu item to various screens within BlackBerry specific applications, or as a system-wide setting. The following example illustrates how to add a menu item to the email view screen.

Obtain an instance of the MenuItemRepository to add the menu item.

Code:
myMenuItem myMenuitem = new MyMenuItem(0);

ApplicationMenuItemRepository
  .getInstance().addMenuItem
  (ApplicationMenuItemRepository
    .MENUITEM_EMAIL_VIEW,myMenuitem);
Create a class so that certain methods within the ApplicationMenuItem class can be overridden.

Code:
class MyMenuItem extends ApplicationMenuItem{

    //using the default constructors here.
    MyMenuItem(int order){
        super(order);
    }

    //methods we must implement
    //Run is called when the menuItem is invoked
    public Object run(Object context){
        //context object should be a email message
        if (context instanceof Message){
            Message message = (Message)context;
            //this is where we would work the message
          //do something here
        }
        return context;
    }

    //toString should return the string we want to
    //use as the lable of the menuItem
    public String toString(){
        return "MyMenu Name";
    }
}
It should be noted that Object context that is passed into the run method will depend on the screen to which the menu item has been added. In this example, the context is an email message because the menu item has been added to the email view screen. If the item was added to the address book, it would return a personal information management (PIM) item.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 10-27-2007, 02:19 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Default j2me programing with BlackBerry phones -useful tips

How To - Add plain text or binary files to an application

The class java.lang.Class contains methods that enable you to import a plain text or a binary file as an input stream. Once the contents of the file are in an input stream it can be read appropriately into the necessary format. Below is an example on how to import a plain text file into an application.

1. Open a text editor and add some text. For example, Test test test
2. Save the file as test.
3. Create a new project.
4. Add the file text to the project.
5. Create a new file called FileDemo.java.

The source for FileDemo.java looks as follows;

Code:
package com.packagename.stuff;


import java.io.*;

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


class FileDemo extends Application {


    public static void main(String args[]) {

        FileDemo theApp = new FileDemo();

        theApp.enterEventDispatcher();

    }


    public FileDemo() {

        try {

            //The class name is the fully qualified package name followed

            //by the actual name of this class

            Class classs = Class.forName("com.packagename.stuff.FileDemo");


            //to actually retrieve the resource prefix the name of the file with a "/"

            InputStream is = classs.getResourceAsStream("/test");


            //we now have an input stream. Create a reader and read out

            //each character in the stream.

            InputStreamReader isr = new InputStreamReader(is);

            char c;

            while ((c = (char)isr.read()) != -1) {

                System.out.print(c);

            }

        } catch(Exception ex) {

            System.out.println("Error: " + ex.toString());

        }

    }

}
When the above demo is run in the simulator the debugger will show the output of "Test test test" or the contents in the test file.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 10-27-2007, 02:20 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

How To - Allow an application to restart itself

A Java application for a BlackBerry device is able to shut down and restart itself. Prior to exiting, the application should stop all threads and free up resources. The following code shows a simple application that will continuously exit and restart itself.

Code:
public final class RestartSample extends Application
{
    public static void main(String[] args)
    {
            RestartSample theApp = new RestartSample();
            theApp.enterEventDispatcher();
    }

    public RestartSample()
    {
       System.out.println("Application started...");

        //Get the current application descriptor.
        ApplicationDescriptor current = ApplicationDescriptor.currentApplicationDescriptor();
        System.out.println("Scheduling the restart in 1 minute...");
        
        //Schedules are rounded to the nearest minute so ensure the application is scheduled for at least 1 minute in the future.
ApplicationManager.getApplicationManager().scheduleApplication(current, System.currentTimeMillis() + 60001, true);

        System.out.println("Application is exiting...");
        System.exit(0);
    }
}
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 10-27-2007, 02:21 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow Re: j2me programing with BlackBerry phones -useful tips

How to - Capture power change events

Your application can be notified when power change events take place on the BlackBerry device. This could be used to halt certain features when the battery power is low, and resume them when it is back to normal levels. Implementing the SystemListener interface (net.rim.device.api.system.SystemListener) can perform these operations. Events such as the BlackBerry powering on, powering off, and changes in the battery state can be captured. The following sample application shows how to implement the SystemListener interface:
Code:
/**
 * PowerChangeEvent.java
 *
 */

import java.util.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;

public class PowerChangeEvent
  extends Application implements SystemListener
{
  public static PowerChangeEvent theApp;

  public static void main(String args[])
  {
    theApp = new PowerChangeEvent();
    theApp.enterEventDispatcher();
  }

  public PowerChangeEvent()
  {
    //Register this instance with the system listener.
    Application.getApplication().addSystemListener(this);
    System.out.println("PowerChangeEvent: PowerChangeEvent has started!");
  }

  //Invoked when the user is putting the device into a power off state.
  public void powerOff()
  {
    System.out.println("PowerChangeEvent: The BlackBerry is powering off.");
  }

  //Invoked when the device has left the power off state.
  public void powerUp()
  {
    System.out.println("PowerChangeEvent: The BlackBerry is powering up.");
  }

  //Invoked when the internal battery voltage falls below a critical level.
  public void batteryLow()
  {
    System.out.println("PowerChangeEvent: The battery is getting low!");
  }

  //Invoked when the internal battery voltage has returned to normal.
  public void batteryGood()
  {
    System.out.println("PowerChangeEvent: The battery level is now good!");
  }

  //Invoked when the internal battery state has changed.
  //Not used in this sample.
  public void batteryStatusChange(int status)
  {
  }
}
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 10-27-2007, 02:23 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow Re: j2me programing with BlackBerry phones -useful tips

How to - Code time-sensitive applications

Calculating Time on the Device


The time on the BlackBerry device is calculated since midnight, January 1, 1970 Universal Time Coordinate (UTC) with absolute time as milliseconds. Time on the device is typically measured in either CPU ticks or milliseconds.

Handling System Time Zone Changes


If you are caching a time-sensitive object for performance reasons, remember that the system time zone can change on the device. When the time zone changes, the system sends out a global event message to the applications. To catch it, implement the GlobalEventListener interface and register the listener by calling Application.addGlobalEventListener(). Your eventOccurred() method should look similar to this:

Code:
public void eventOccurred
(
   long guid,
   int data0,
   int data1,
   Object object0,
   Object object1
){
   if(guid == DateTime.GUID_TIMEZONE_CHANGED) {
       _cal.setTimeZone(TimeZone.getDefault());
   }
}
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 10-27-2007, 02:26 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow j2me programing with BlackBerry phones -useful tips

How To - Display a GUI when the BlackBerry device starts up

An auto-start application that pushes a screen upon start-up must wait for the Graphical User Interface (GUI) process to finish loading when a BlackBerry device is rebooted or restarted. To do this, you can check the ApplicationManager.inStartup() and delay the push of the screen. The inStartup() method will return true if the device is in a start-up process, otherwise it will be false. The following code sample creates outlines on how to use the ApplicationManager.inStartup() method:

Code:
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;

public class SampleApplication extends UiApplication {
      private Thread _thread;

      public static void main(String[] args) {
             SampleApplication App = new SampleApplication();
             App.enterEventDispatcher();
      }

      public SampleApplication() {
             _thread = new Thread(new checkRequest());
             _thread.start();
      }

      public class checkRequest extends Thread {{
            public void run() {
            // Creates an instance of the system’s application manager.

                  ApplicationManager myApp =
                                ApplicationManager.getApplicationManager();
                  while(myApp.inStartup()) {
                        try {
                               _thread.sleep(2000);
                        } catch(Exception e) {
                              // Catch Exception
                        }
                  }

               UiApplication.getUiApplication().invokeLater(new Runnable() {
                         public void run() {
                               pushScreen(new MyMainScreen());
                        }
              });
               UiApplication.getUiApplication().requestForeground();
            }
}

final class MyMainScreen extends MainScreen {
      public MyMainScreen() {
             super();
             BasicEditField field1 = new BasicEditField("Test:","");
             add(field1);
      }
}
}
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 10-27-2007, 02:27 AM
jeyaprakash.c jeyaprakash.c is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 228
jeyaprakash.c is on a distinguished road
Arrow Re: j2me programing with BlackBerry phones -useful tips

How To - Enable the backlight and prevent the screen from turning off

Some BlackBerry device screens, such as those on the BlackBerry 7100 series, become blank when not in use. BlackBerry device users can configure the screen timeout period.

You might prefer to control when the screen is turned on or off. For example, when implementing a peripheral keyboard you can simulate key events to make sure that the screen does not turn off while the BlackBerry device user types or navigates on the BlackBerry device.

The following code specifies that the screen backlight, once activated, has a timeout period of 30 seconds.

Code:
if(( Display.getProperties()
  & Display.DISPLAY_PROPERTY_REQUIRES_BACKLIGHT) != 0 )
{
    Backlight.enable( true, 30 );
}
The backlight.enable method only turns the backlight on for the period of time specified, up to a maximum of 255 seconds. BlackBerry device user activity that occurs while the backlight is on resets the value specified in this method.

However, some applications might require the backlight to stay on for longer than 255 seconds. For example, in navigation software design, the backlight might be required for extended periods of time even though BlackBerry device user activity is not continuous (e.g., while travelling). For this scenario, you can set a timer to turn the backlight on every 255 seconds.

Remember that BlackBerry device backlight usage consumes additional power. Excessive usage has a negative impact on the BlackBerry device battery.

Note: The code sample above requires code signing. See the Controlled APIs and Code Signing page for more information.
__________________
thanx n regards
jeyaprakash.c
Add Post to del.icio.usBookmark Post in Technorati