Java- I/O, SMS etc N Amanquah
File I/O RecordStore SMS Assorted
FileI/O- output –chap 15 FileConnection API of the GCF provides the streams for I/O String url=“file:///root1/photos/myfile” FileConnection fc = (FileConnection)Connector.open(url); try { if (!fc.exists()) fc.create(); OutputStream rawOut = fc.openOutputStream(); PrintStream out = new PrintStream(rawOut); try { out.println(“Hello into a file"); } finally { out.close(); } } finally { fc.close(); }
FileI/O-input String url=“file:///root1/photos/myfile” FileConnection fc = (FileConnection)Connector.open(url); try { Inputstream in =fc.openInputStream(); //in.read() //read from file } finally { in.close(); } finally { fc.close(); }
File I/O See API for other interesting functions Install app by OTA to have private directory for midlet created by emulator. Access to system folders: String system.getProperty(“fileconn.dir.photos”) If returns a directory URL or NULL fileconn.dir.videos fileconn.dir.graphics fileconn.dir.tones fileconn.dir.music fileconn.dir.recordings
File I/O Example –kb 15 illustrates creating a directory, file, write & read, remove file & dir. Application must be signed to suppress all the notifications Fileconnection is cleaner, consistent on most devices Can access images, sounds, other files App must be signed.(permissions)
RecordStore –chap 14 Recordstore data is for midlet suite. (by default) RecordStore rs=RecordStore.openRecordStore(“name”, true) //true= create if one does not exist Write: Byte[] data… Int id=rs.addRecord(data, 0,data.length) Read: Byte[] rec=rs.getRecord(id) //read a particular record
RecordStore while (re.hasNextElement()) { To obtain id to use: RecordEnumeration re=rs.enumerateRecords(null,null,false) 3 Params: recordFilter, recordComparator, keepCurrentIfChanged? To fetch all records, use: while (re.hasNextElement()) { byte[] record = re.nextRecord(); ….//process the records See kb 14: in following code, store and read back key-value pairs
RecordStore-write RecordStore rs = RecordStore.openRecordStore(mName, true); try { Enumeration keys = mMap.keys(); while (keys.hasMoreElements()) { String key = (String)keys.nextElement(); String value = (String)mMap.get(key); byte[] record = packRecord(key, value); rs.addRecord(record, 0, record.length); } catch (IOException ioe) { System.out.println("Error packing in " + mName + " : " + key + " -> " + value); finally { rs.closeRecordStore(); } private byte[] packRecord(String key, String value) throws IOException { ByteArrayOutputStream raw = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(raw); out.writeUTF(key); out.writeUTF(value); return raw.toByteArray();
RecordStore-read private void read() throws RecordStoreException { RecordStore rs = RecordStore.openRecordStore(mName, true); mMap = new Hashtable(); try { RecordEnumeration re = rs.enumerateRecords(null, null, false); while (re.hasNextElement()) { byte[] record = re.nextRecord(); parseRecord(record); } finally { rs.closeRecordStore(); } private void parseRecord(byte[] record) { ByteArrayInputStream raw = new ByteArrayInputStream(record); DataInputStream in = new DataInputStream(raw); String key = in.readUTF(); String value = in.readUTF(); mMap.put(key, value); catch (IOException ioe) { System.out.println("Bad record in " + mName + ".");
Messaging –chap 19 WMA =wireless messaging API, both sms & mms Based on the GCF, use the Connetor to get MessageConnection Import javax.wireless.messaging 4 lines of code to send sms obtain a connector Get a message with newMessage() Fill the message ie setPayLoad() Send()
Sending SMS import javax.wireless.messaging Public void sendText(String addr, String text) throws IOException, InterruptedException{ String cs=“sms://”+addr + port; MessageConnection mc=(MessageConnection)Connector.open(cs); TextMessage tm=(TextMessage)mc.newMessage(MessageConnection. TEXT_MESSSAGE); tm.setPayloadText(text); mc.send(tm) } //NB: port number is optional, if omitted= normal text msg
Receiving SMS Create a MessageConnection without a destination string Put application in push registry, (with a static registration) Two options: Loop on MessageConnection ‘s receive() method (thread) (it blocks) Use a thread to listen for incoming messages. Register a listener. Its notifyIncomingMessage() will be called See kb-19
Push registry Allows incoming network connection to launch up application To register, provide Connection string eg sms://:50000 A class name that describes the midlet to be launched. String representing allowed senders (use * for all connections) Dynamic registration – see chapter 6 To register: Make the ff calls from within a thread: PushRegistry.registerConnection(connStr, midletName, “*”) To unregister: PushRegistry.unregisterConnection(connStr) //only one param
Push registry- static registration Go to project properties Application Descriptor push registry add. To find incomming connections, call PushRegistry’s listConnections(), pass false to get every input Returns array of connections. Run kb-06 OTA whether static or dyanamic registration is used. Use the WMA utility console to send sms to the emulator
Push registry- timed execution Dynamic ! Call PushRegistry.registerAlarm(“midletname”, long_time) Do this in a thread, ie the registration. Run kb-06 OTA
Other topics Cool methods: boolean Display. flashBacklight(int duration) boolean Display. vibrate(int duration) (both return false if feature is not supported, duration in ms) Contacts & Calendar: chapter 16 of kickbutt book Parsing XML: chapter 21 Parsing RSS: chapter 21
Use of Netbeans Drag and Drop approach to app development
Lab work Build an application that does the following: Make use of netbeans: Fetch data from the user (the user’s preferences) Send it by sms to another number. Store the data you have collected in a record store so that it can be retrieved the next time the user runs the program. One menu item should allow the user to enter the values afresh, or to fetch the saved values.