×
Namespaces

Variants
Actions
(Difference between revisions)

Checking battery level in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
vltsoy (Talk | contribs)
(New page: __NOTOC__ __NOEDITSECTION__ {{CodeSnippet |id=  |platform=S60 3rd Edition, FP2 |devices=Nokia E70, Nokia N78 |category=Java ME |subcategory=Hardware |creationdate=October 30, 2008 |ke...)
 
vltsoy (Talk | contribs)
Line 6: Line 6:
 
|devices=Nokia E70, Nokia N78
 
|devices=Nokia E70, Nokia N78
 
|category=Java ME
 
|category=Java ME
|subcategory=Hardware
+
|subcategory=System information
 
|creationdate=October 30, 2008
 
|creationdate=October 30, 2008
|keywords=java.lang.System.getProperty(), javax.microedition.io.Connector.open(), javax.microedition.io.file.FileConnection.availableSize()
+
|keywords=java.lang.System.getProperty, com.nokia.mid.batterylevel
 
}}
 
}}
 +
  
 
==Overview==
 
==Overview==
The code snippet demonstrates how memory card availability can be checked.
 
  
App uses <tt>System.getProperty</tt> method to check API version and
+
This code snippet demonstrates how to retrieve current battery level.
memory card drive path.
+
After the path have been retrieved app establishes a file connection using
+
<tt>Connector.open</tt> method and gets available amount of space on the memory
+
card by calling <tt>FileConnection.availableSize</tt>.
+
  
==Source file: CheckingMemoryCard.java==
+
Application retrieves system property <tt>com.nokia.mid.batterylevel</tt>,
 +
which contains current battery level in percentage, and displays it.
 +
 
 +
==Source file: BatteryLevel.java==
  
 
<code java>
 
<code java>
import javax.microedition.io.Connector;
+
 
import javax.microedition.io.file.FileConnection;
+
 
import javax.microedition.lcdui.Command;
 
import javax.microedition.lcdui.Command;
 
import javax.microedition.lcdui.CommandListener;
 
import javax.microedition.lcdui.CommandListener;
Line 30: Line 28:
 
import javax.microedition.lcdui.Displayable;
 
import javax.microedition.lcdui.Displayable;
 
import javax.microedition.lcdui.Form;
 
import javax.microedition.lcdui.Form;
 +
import javax.microedition.lcdui.StringItem;
 
import javax.microedition.midlet.MIDlet;
 
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
+
 
/**
+
public class BatteryLevel extends MIDlet implements CommandListener{
* MIDP is an example checking memory card availability.
+
 
*/
+
public class CheckingMemoryCard extends MIDlet implements CommandListener {
+
 
     private Display display;
 
     private Display display;
    /**
+
     private Form form;
    * For displaying results.
+
     private Command exitCommand;
    */
+
     private Command refreshCommand;
     private Form frmMain;
+
     private StringItem level;
     /**
+
 
    * Calls exitMIDlet method.
+
 
    */
+
     private Command cmdExit;
+
     /**
+
    * Starts MC-checking procedure.
+
    */
+
    private Command cmdCheck;
+
 
     /**
 
     /**
 
     * Constructor. Constructs the object and initializes displayables.
 
     * Constructor. Constructs the object and initializes displayables.
 
     */
 
     */
     public CheckingMemoryCard() {
+
     public BatteryLevel() {
         InitializeComponents();
+
         form = new Form("Battery level.");
    }
+
 
    /**
+
        exitCommand = new Command("Exit", Command.EXIT, 2);
    * Initializes a ListBox object and adds softkeys.
+
        refreshCommand = new Command("Refresh", Command.OK, 1);
    */
+
 
    protected void InitializeComponents() {
+
        level = new StringItem("Current battery level:", "");
         display = Display.getDisplay( this );
+
        form.append(level);
         //initializing device list
+
 
        frmMain = new Form( "MC Info" );
+
        form.addCommand(exitCommand);
 +
        form.addCommand(refreshCommand);
 +
        form.setCommandListener(this);
 +
 
 +
         display = Display.getDisplay(this);
 +
         display.setCurrent(form);
 
          
 
          
         cmdExit = new Command( "Exit", Command.EXIT, 1 );
+
         checkBatteryLevel();
        cmdCheck = new Command( "Check", Command.SCREEN, 1);
+
       
+
        frmMain.addCommand( cmdExit );
+
        frmMain.addCommand( cmdCheck );
+
        frmMain.setCommandListener( this );       
+
 
     }
 
     }
   
+
 
 
     /**
 
     /**
 
     * From MIDlet.
 
     * From MIDlet.
     * Called when MIDlet is started.
+
     * Called when the MIDlet is started.
    * @throws javax.microedition.midlet.MIDletStateChangeException
+
 
     */
 
     */
     public void startApp() throws MIDletStateChangeException {      
+
     public void startApp() {
         display.setCurrent( frmMain );
+
         // No implementation required.
 
     }
 
     }
 +
 
     /**
 
     /**
 
     * From MIDlet.
 
     * From MIDlet.
Line 84: Line 75:
 
     */
 
     */
 
     public void pauseApp() {
 
     public void pauseApp() {
         //No implementation required
+
         // No implementation required.
 
     }
 
     }
 +
 
     /**
 
     /**
 
     * From MIDlet.
 
     * From MIDlet.
Line 91: Line 83:
 
     * @param unconditional whether the MIDlet has to be unconditionally
 
     * @param unconditional whether the MIDlet has to be unconditionally
 
     * terminated
 
     * terminated
    * @throws javax.microedition.midlet.MIDletStateChangeException
 
 
     */
 
     */
     public void destroyApp(boolean unconditional)  
+
     public void destroyApp(boolean unconditional) {
        throws MIDletStateChangeException {      
+
         // No implementation required
         exitMIDlet();
+
 
     }
 
     }
 +
 
     /**
 
     /**
 
     * From CommandListener.
 
     * From CommandListener.
 
     * Called by the system to indicate that a command has been invoked on a
 
     * Called by the system to indicate that a command has been invoked on a
 
     * particular displayable.
 
     * particular displayable.
     * @param command the command that was invoked
+
     * @param cmd the command that was invoked
 
     * @param displayable the displayable where the command was invoked
 
     * @param displayable the displayable where the command was invoked
 
     */
 
     */
     public void commandAction( Command command, Displayable displayable ) {
+
     public void commandAction(Command c, Displayable d) {
       
+
         if (c == refreshCommand) {
         if( command == cmdExit ) {  
+
             checkBatteryLevel();
             exitMIDlet();
+
         } else if (c == exitCommand) {
         }
+
             notifyDestroyed();
        if( command == cmdCheck ) {
+
             //checking API version
+
            if( !checkAPIVersion() )
+
                return;
+
            //getting Localized UI name for the memory card
+
            checkMCDirName();
+
            //checking Root directory of a memory card
+
            if( !checkMCRoot() )
+
                return;
+
            //if Root directory retrieved in the previous step
+
            //then we do a file connection test
+
            checkMCConnection();
+
 
         }
 
         }
 
     }
 
     }
 +
 
     /**
 
     /**
     * Method calls stopDiscover method and notifyDestroyed after that.
+
     * Called to read current battery level.
 
     */
 
     */
     protected void exitMIDlet() {
+
     private void checkBatteryLevel() {
         notifyDestroyed();
+
         String property = System.getProperty("com.nokia.mid.batterylevel");
    }
+
         level.setText("\n"+property+"%");
    /**
+
    * Adds a StringItem to the frmMain.
+
    * @param strPrint string to add to frmMain.
+
    * @see Form#append(java.lang.String)
+
    * @see Form
+
    */
+
    protected void printToFrm( String strPrint ) {
+
        frmMain.append( strPrint );
+
    }
+
    /**
+
    * Gets JSR-75 API version using MIDP system property and
+
    * check whether it is null or not.
+
    * @return true if version detected and false otherwise.
+
    */
+
    protected boolean checkAPIVersion() { 
+
        String fileconVer =  
+
                System.getProperty(  
+
                "microedition.io.file.FileConnection.version" );
+
         printToFrm( "Getting JSR-75 API version..." );
+
        if( fileconVer != null ) {
+
            printToFrm( "Version : " + fileconVer );
+
        } else {
+
            printToFrm( "Version NOT found!");
+
            return false;
+
        }
+
        return true;
+
    }
+
    /**
+
    * Gets Localized MC directory name using MIDP system property and
+
    * check whether it is null or not.
+
    * @return true if name detected and false otherwise.
+
    */
+
    private boolean checkMCDirName() {
+
        String nameMC = System.getProperty( "fileconn.dir.memorycard.name" );
+
        printToFrm( "Getting MC directory name ..." );
+
        if( nameMC != null ) {
+
          printToFrm( "MC directory name : " + nameMC );
+
        } else {
+
            printToFrm( "MC directory name NOT found!");
+
            return false;
+
        }
+
        return true;
+
    }
+
    /**
+
    * Gets MC directory connection URL using MIDP system property and
+
    * check whether it is null or not.
+
    * @return true if URL detected and false otherwise.
+
    */
+
    private boolean checkMCRoot() {
+
        String rootMC = System.getProperty( "fileconn.dir.memorycard" );
+
        printToFrm( "Getting MC root ..." );           
+
        if( rootMC != null ) {
+
            printToFrm( "MC root : " + rootMC );
+
            } else {
+
                printToFrm( "MC root NOT found!");
+
                return false;
+
            }
+
        return true;
+
    }
+
    /**
+
    * Gets MC directory connection URL using MIDP system property and
+
    * check whether it is null or not.
+
    * @return true if URL detected and false otherwise.
+
    */
+
    private boolean checkMCConnection() {
+
        String rootMC = System.getProperty( "fileconn.dir.memorycard" );
+
        FileConnection fconn = null;
+
        try {
+
            fconn = (FileConnection)Connector.open( rootMC );
+
            printToFrm( "Getting available size ...");
+
            printToFrm( "Size: " + ( fconn.availableSize() / 1024 ) + "KB" );
+
            printToFrm( "Closing file connection...");
+
            fconn.close();
+
        } catch ( Exception e ) {
+
            printToFrm( e.toString() );
+
            return false;
+
        }
+
        return true;
+
 
     }
 
     }
 
}
 
}
  
</code>
 
  
==Postconditions==
+
</code>
  
When "Check" command is being pressed the folowing steps are executed:
+
==Postconditions==
  
-API availability check. If found it is printed to the form;
+
This code will display current battery level in percentage.
  
-getting Localized UI name for the memory card. If found it is printed to the form;
+
==Supplementary material==
  
-checking Root directory of a memory card. If found it is printed to the form;
+
You can see source file and executable application in attached zip archive. Archive is available for download at [[Media:Checking_battery_level_in_J2ME.zip]]
 
+
-then we do a file connection test. Available size printed to the form if connection
+
was successful.
+
 
+
 
+
==Supplementary material==
+
You can see source file and executable application in attached zip archive. Archive is available for download at [[Media:Checking_memory_card_in_Java_ME.zip]]
+
  
 
[[Category:Java ME]][[Category:Code Examples]]
 
[[Category:Java ME]][[Category:Code Examples]]

Revision as of 17:59, 27 November 2008


Article Metadata
Tested with
Devices(s): Nokia E70, Nokia N78
CompatibilityArticle
Keywords: java.lang.System.getProperty, com.nokia.mid.batterylevel
Created: (30 Oct 2008)
Last edited: vltsoy (27 Nov 2008)


Overview

This code snippet demonstrates how to retrieve current battery level.

Application retrieves system property com.nokia.mid.batterylevel, which contains current battery level in percentage, and displays it.

Source file: BatteryLevel.java

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
 
public class BatteryLevel extends MIDlet implements CommandListener{
 
private Display display;
private Form form;
private Command exitCommand;
private Command refreshCommand;
private StringItem level;
 
 
/**
* Constructor. Constructs the object and initializes displayables.
*/

public BatteryLevel() {
form = new Form("Battery level.");
 
exitCommand = new Command("Exit", Command.EXIT, 2);
refreshCommand = new Command("Refresh", Command.OK, 1);
 
level = new StringItem("Current battery level:", "");
form.append(level);
 
form.addCommand(exitCommand);
form.addCommand(refreshCommand);
form.setCommandListener(this);
 
display = Display.getDisplay(this);
display.setCurrent(form);
 
checkBatteryLevel();
}
 
/**
* From MIDlet.
* Called when the MIDlet is started.
*/

public void startApp() {
// No implementation required.
}
 
/**
* From MIDlet.
* Called to signal the MIDlet to enter the Paused state.
*/

public void pauseApp() {
// No implementation required.
}
 
/**
* From MIDlet.
* Called to signal the MIDlet to terminate.
* @param unconditional whether the MIDlet has to be unconditionally
* terminated
*/

public void destroyApp(boolean unconditional) {
// No implementation required
}
 
/**
* From CommandListener.
* Called by the system to indicate that a command has been invoked on a
* particular displayable.
* @param cmd the command that was invoked
* @param displayable the displayable where the command was invoked
*/

public void commandAction(Command c, Displayable d) {
if (c == refreshCommand) {
checkBatteryLevel();
} else if (c == exitCommand) {
notifyDestroyed();
}
}
 
/**
* Called to read current battery level.
*/

private void checkBatteryLevel() {
String property = System.getProperty("com.nokia.mid.batterylevel");
level.setText("\n"+property+"%");
}
}

Postconditions

This code will display current battery level in percentage.

Supplementary material

You can see source file and executable application in attached zip archive. Archive is available for download at Media:Checking_battery_level_in_J2ME.zip

209 page views in the last 30 days.