Monday, March 11, 2019

Android开发笔记-ch3.4.6 Sending email from APP 3.4.7 Socket/ServerSocket


3.4.6 Sending email from APP

Refer to SO and SO.
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
            "mailto","abc@gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
Or:
try {   
    GMailSender sender = new GMailSender("username@gmail.com", "password");
    sender.sendMail("This is Subject", "This is Body", "user@gmail.com", "user@yahoo.com");   
} catch (Exception e) { Log.e("SendMail", e.getMessage(), e);} 
 

3.4.7 Socket/ServerSocket

Refer to SO, Socket, ServerSocket and example. Socket is for client side, and ServerSocket is for server side. Sample code refer to this. For server side, the main Activity creates a server thread to listen for connection request (has to be a thread to avoid block the main UI thread). Once a connection is established, the server thread will spaw another communication thread for handling communication throught that socket, and the server thread will listen for new connection request. This way, it will allow multiple clients connect to the server.
Note for the client side code, here is my understanding: the ClientThread will be terminated after created the socket. However, since the socket is a member of the main Acitivity, so the socket won't be destroyed and can be referenced inside onClick().
Assume the socket can be connected very quick, there is no need to create a thread to create the socket, right? No, it will cause exception: android.os.networkonMainThreadException. At android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork().
If not redirecting the port, should use same port in the client and the server code.
Here is a SO post for the server code to figure out its own IP address and can promt user this info for convenience. Two ideas there, either using Android WIFI manager or pure Java code for all Linux:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

/** Pure Java way:
     * Returns MAC address of the given interface name.
     * @param interfaceName “eth0”, “wlan0” or NULL=use first interface
     * @return  mac address or empty string
     */
public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces= Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac==null) return "";
            StringBuilder buf = new StringBuilder();
            for (int idx=0; idx<mac.length; idx++) buf.append(String.format("%02X:", mac[idx]));       
            if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
            return buf.toString();
        }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
    /*try {  // this is so Linux hack
        return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
    } catch (IOException ex) { return null;}*/
}

0 Comments:

Post a Comment