×
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...)
 
hamishwillee (Talk | contribs)
m (Hamishwillee - Add Abstract. Tidy wiki text)
(19 intermediate revisions by 6 users not shown)
Line 1: Line 1:
__NOTOC__
+
[[Category:Java ME]][[Category:Code Examples]][[Category:Base/System]][[Category:Device Management]][[Category:Symbian]][[Category:Series 40]][[Category:Java Runtime 2.3 for Symbian]][[Category:Nokia Belle]][[Category:Series 40 Developer Platform 1.1]][[Category:Series 40 Developer Platform 2.0]]
__NOEDITSECTION__
+
{{ArticleMetaData <!-- v1.2 -->
{{CodeSnippet
+
|sourcecode= [[Media:BatteryLevelSource.zip]]
|id=&nbsp;
+
|installfile= [[Media:BatteryLevelBinaries.zip]]
|platform=S60 3rd Edition, FP2
+
|devices= Nokia E70, Nokia N78, Nokia 701, Nokia Asha 305
|devices=Nokia E70, Nokia N78
+
|sdk= [http://www.developer.nokia.com/Develop/Java/Tools/ Nokia SDK 1.1 for Java], [http://www.developer.nokia.com/Develop/Java/Tools/ Nokia SDK 2.0 for Java]
|category=Java ME
+
|platform= Series 40, Symbian
|subcategory=Hardware
+
|devicecompatability= <!-- Compatible devices (e.g.: All* (must have GPS) ) -->
|creationdate=October 30, 2008
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|keywords=java.lang.System.getProperty(), javax.microedition.io.Connector.open(), javax.microedition.io.file.FileConnection.availableSize()
+
|signing= <!-- Empty or one of Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 +
|keywords= java.lang.System.getProperty, com.nokia.mid.batterylevel
 +
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= <!-- After re-review: [[User:username]] -->
 +
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 +
|update-by= <!-- After significant update: [[User:username]]-->
 +
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 +
|creationdate= 20081127
 +
|author= [[User:Vltsoy]]
 +
<!-- The following are not in current metadata -->
 +
|id= CS001201
 
}}
 
}}
  
 
==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
+
{{Abstract|This code snippet demonstrates how to retrieve the 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==
+
The application retrieves the system property {{Icode|com.nokia.mid.batterylevel}} which contains the current battery level (in per cent) and displays it. Note that in Series 40 platform only signed MIDlets under operator domain can retrieve this information.
 +
 
 +
==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 39:
 
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;
+
 
/**
+
       
* MIDP is an example checking memory card availability.
+
public class BatteryLevel extends MIDlet implements CommandListener{
*/
+
 
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("", "");
        display = Display.getDisplay( this );
+
        form.append(level);
        //initializing device list
+
 
        frmMain = new Form( "MC Info" );
+
        form.addCommand(exitCommand);
       
+
        form.addCommand(refreshCommand);
         cmdExit = new Command( "Exit", Command.EXIT, 1 );
+
        form.setCommandListener(this);
         cmdCheck = new Command( "Check", Command.SCREEN, 1);
+
 
 +
        display = Display.getDisplay(this);
 +
        display.setCurrent(form);
 
          
 
          
         frmMain.addCommand( cmdExit );
+
         checkBatteryLevel();
        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 87:
 
     */
 
     */
 
     public void pauseApp() {
 
     public void pauseApp() {
         //No implementation required
+
         // No implementation required.
 
     }
 
     }
 +
 
     /**
 
     /**
 
     * From MIDlet.
 
     * From MIDlet.
Line 91: Line 95:
 
     * @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");
    }
+
         if (property == null) {
    /**
+
             level.setLabel("Error:\n");
    * Adds a StringItem to the frmMain.
+
            level.setText("Unable to retrieve current battery level.\n" +
    * @param strPrint string to add to frmMain.
+
                          "It's only available for signed midlets " +
    * @see Form#append(java.lang.String)
+
                          "under operator domain.");
    * @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 {
 
         } else {
            printToFrm( "Version NOT found!");
+
        level.setLabel("Current battery level:");
            return false;
+
        level.setText("\n"+property+"%");
 
         }
 
         }
        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>
  
</code>
+
==Postconditions==
 
+
==Postconditions==  
+
 
+
When "Check" command is being pressed the folowing steps are executed:
+
 
+
-API availability check. If found it is printed to the form;
+
 
+
-getting Localized UI name for the memory card. If found it is printed to the form;
+
 
+
-checking Root directory of a memory card. If found it is printed to the form;
+
 
+
-then we do a file connection test. Available size printed to the form if connection
+
was successful.
+
  
 +
This code displays the current battery level in per cent.
  
 
==Supplementary material==
 
==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]]
+
The example project and binary files are available for download at [[Media:BatteryLevelSource.zip]] and [[Media:BatteryLevelBinaries.zip]].

Revision as of 09:26, 5 October 2012

Article Metadata
Code ExampleTested with
Devices(s): Nokia E70, Nokia N78, Nokia 701, Nokia Asha 305
CompatibilityArticle
Keywords: java.lang.System.getProperty, com.nokia.mid.batterylevel
Created: vltsoy (27 Nov 2008)
Last edited: hamishwillee (05 Oct 2012)

Contents

Overview

This code snippet demonstrates how to retrieve the current battery level.

The application retrieves the system property com.nokia.mid.batterylevel which contains the current battery level (in per cent) and displays it. Note that in Series 40 platform only signed MIDlets under operator domain can retrieve this information.

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("", "");
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");
if (property == null) {
level.setLabel("Error:\n");
level.setText("Unable to retrieve current battery level.\n" +
"It's only available for signed midlets " +
"under operator domain.");
} else {
level.setLabel("Current battery level:");
level.setText("\n"+property+"%");
}
}
}

Postconditions

This code displays the current battery level in per cent.

Supplementary material

The example project and binary files are available for download at Media:BatteryLevelSource.zip and Media:BatteryLevelBinaries.zip.

194 page views in the last 30 days.