Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 26
Текст из файла (страница 26)
Once we have finished with the OutputStreamwe can close it.Having written the request we are now ready to read the response. Weuse our SocketConnection to get a DataInputStream and use theread() method to read from it in the standard manner.DataInputStream in = conn.openDataInputStream();int ch;while ( (ch = in.read()) != -1 &&sM.textBox.size() < sM.textBox.getMaxSize()) {...}MIDP 2.0119Figure 3.6 Socket Demo MIDlet running on a Nokia 6600.The response from the web server should be a stream of raw HTML.We read the stream until our MIDlet’s TextBox is full and then close theconnection (reading the response in its entirety is likely to be a lengthyprocess for most web sites!).The screenshots in Figure 3.6 show the Socket Demo MIDlet runningon a Nokia 6600.Note that the purpose of this sample code is to demonstrate how touse client TCP socket connections.
Normally, to make requests to a HTTPserver we would use an HttpConnection or HttpsConnection.Also, under the JTWI security policy for GSM/UMTS compliant devices,the implementation of SocketConnection using TCP sockets mustthrow a SecurityException when an untrusted MIDlet suite attemptsto connect on ports 80, 8080 (HTTP) and 443 (HTTPS). Hence the abovecode is not future-proof for untrusted MIDlet suites.3.3.5 The Push Registry3.3.5.1 IntroductionOne of the exciting new additions to MIDP 2.0 is the Push Registry API,which allows MIDlets to be launched in response to incoming networkconnections.
Many applications, particularly messaging applications,need to be continuously listening for incoming messages. Previously,to achieve this a Java application would have had to be continuallyrunning in the background. Although the listening Java application mayitself be small, it would still require an instance of the virtual machineto be running, thus appropriating some of the mobile phone’s scarceresources. The JSR 118 recognized the need for an alternative, moreresource-effective solution for MIDP 2.0 and so introduced the pushregistry.120MIDP 2.0 AND THE JTWI3.3.5.2 Using the Push RegistryThe Push Registry API is encapsulated in the javax.microedition.io.PushRegistry class. The push registry maintains a list of inboundconnections that have been previously registered by installed MIDlets.A MIDlet registers an incoming connection with the push registry eitherstatically at installation via an entry in the JAD file or dynamically(programmatically) via the registerConnection() method.When a MIDlet is running, it handles all the incoming connections(whether registered with the push registry or not).
If, however, the MIDletis not running, the AMS listens for registered incoming connections andlaunches the MIDlet in response to an incoming connection previouslyregistered by that MIDlet, by invoking the startApp() method. TheAMS then hands off the connection to the MIDlet which is then responsiblefor opening the appropriate connection and handling the I/O.In the case of static registration, the MIDlet registers its interest inincoming connections in the JAD file, in the following format:MIDlet-Push-<n>: <ConnectionURL>, <MIDletClassName>, <AllowedSender>The <ConnectionURL> field specifies the protocol and port for theconnection end point in the same URI syntax used as the argument to theConnector.open() method that is used by the MIDlet to process theincoming connection. Examples of <ConnectionURL> entries might be:sms://:1234socket://:1234The <MIDletClassName> field contains the package-qualified nameof the class that extends javax.microedition.midlet.MIDlet.This would be the name of the MIDlet class as listed in the applicationdescriptor or manifest file under the MIDlet-<n> entry.The <AllowedSender> field acts as a filter indicating that the AMSshould only respond to incoming connections from a specific sender.For the SMS protocol, the <AllowedSender> entry is the phone number of the required sender.
For a server socket connection endpointthe <AllowedSender> entry would be an IP address (note in bothcases that the sender port number is not included in the filter). The<AllowedSender> syntax supports two wildcard characters: * matchesany string including an empty string and ? matches any character. Hencethe following would be valid entries for the <AllowedSender> field:*129.70.40.*129.70.40.23?MIDP 2.0121The first entry indicates any IP address, the second entry allows thelast three digits of the IP address to take any value, while the last entryallows only the last digit to have any value.So the full entry for the MIDlet-Push-<n> attribute in a JAD file maylook something like this:MIDlet-Push-1: sms://:1234, com.symbian.devnet.ChatMIDlet, *MIDlet-Push-2: socket://:3000, com.symbian.devnet.ChatMIDlet,129.70.40.*If the request for a static connection registration can not be fulfilledthen the AMS must not install the MIDlet.
Examples of when a registrationrequest might fail include the requested protocol not being supportedby the device, or the requested port number being already allocated toanother application.To register a dynamic connection with the AMS we use the staticregisterConnection() method of PushRegistry:PushRegistry.registerConnection(“sms://:1234”,“com.symbian.devnet.ChatMIDlet”, “*”);The arguments take precisely the same format as those used to make upthe MIDlet-Push-<n> entry in a JAD or manifest.
Upon registration,the dynamic connection behaves in an identical manner to a staticconnection registered via the application descriptor.To un-register a dynamic connection the static boolean unregisterConnection() method of PushRegistry is used:boolean result = PushRegistry.unregisterConnection((“sms://:1234”);If the dynamic connection was successfully unregistered a value oftrue is returned.The AMS will respond to input activity on a registered connectionby launching the corresponding MIDlet (assuming that the MIDlet isnot already running). The MIDlet should then respond to the incomingconnection by launching a thread to handle the incoming data in thestartApp() method.
Using a separate thread is the recommendedpractice for avoiding conflicts between blocking I/O operations and thenormal user interaction events. For a MIDlet registered for incoming SMSmessages, the startApp() method might look something like this:public void startApp() {// List of active connections.String[] connections = PushRegistry.listConnections(true);122MIDP 2.0 AND THE JTWIfor (int i=0; i < connections.length; i++) {if(connections[i].equals(“sms://:1234”)){new Thread(){public void run(){Receiver.openReceiver();}}.start();}}...}One other use of the push registry should be mentioned before weleave this topic.
The PushRegistry class provides the registerAlarm() method:public static long registerAlarm(String midlet, long time)This allows a running MIDlet to register itself or another MIDlet inthe same suite for activation at a given time. The midlet argument isthe class name of the MIDlet to be launched at the time specified bythe time argument. The launch time is specified in milliseconds sinceJanuary 1, 1970, 00:00:00 GMT. The push registry may contain only oneoutstanding activation time entry per MIDlet in each installed MIDletsuite. If a previous activation entry is registered, it will be replaced bythe current invocation and the previous value returned. If no previouswakeup time has been set, a zero is returned.3.3.5.3 The Push Registry and the Security ModelThe PushRegistry is a protected API and, as such, a signedMIDlet suite which registers connections statically or contains MIDletswhich register connections and/or alarms, must explicitly requestthe javax.microedition.io.PushRegistry permission in itsMIDlet-Permissions attribute, for example:MIDlet-Permissions: javax.microedition.io.PushRegistry, ...Note that a signed MIDlet suite must also explicitly request the permissions necessary to open the connection types of any connections itwishes to register either statically or dynamically.
If the protection domainto which the signed MIDlet suite would be bound grants, or potentiallygrants, the requested permission, the MIDlet suite can be installed and theMIDlets it contains will be able to register and deregister connections, andregister alarms, either automatically, or with user permission, dependingon the security policy in effect.MIDP 2.0123Untrusted MIDlets do not require a MIDlet-Permissions entry.Whether access is granted to the Push Registry API will depend on thesecurity policy for the untrusted protection domain in effect on the device.On the Sony Ericsson P900/P908 and Nokia 6600, MIDlets in untrustedMIDlet suites can use the Push Registry APIs (Application Auto-Invocationfunction group) with user permission. On both the 6600 and theP900/P908, the default user permission is set to session.