Cómo enviar un SMS en Java?

Cohen -  
 iso03 -
¡Hola a todos!
Bueno, tenía ganas de programar un pequeño programa en Java que enviara SMS. Pero tengo muchas preguntas:
1) ¿Es posible enviar SMS gratis en Java?
2) ¿Cómo se utiliza la "clase", si es que hay una...? (no la encontré en la API)
3) ¿Hay algo más que deba saber antes de empezar?

¡Gracias de antemano!

12 respuestas

lg2006 Mensajes publicados 12 Fecha de registro   Estado Miembro 3
 
Bonjour à tous, voilà, contrairement à certains, moi je suis sur un projet où je dois réaliser un programme Java pour envoyer des SMS via le modem CDMA. Mais je n'arrive pas à trouver certains packages qui me permettront de faire fonctionner mon programme. Voici les messages d'erreur qui s'affichent après la compilation :
-package javax.comm does not exist
-package org.apache.log4j does not exist
-cannot find symbol class logger
Voici le code :
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TooManyListenersException;

import javax.comm.CommDriver;
import javax.comm.CommPortIdentifier;
import javax.comm.CommPortOwnershipListener;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;

import org.apache.log4j.Logger;

class Sms implements SerialPortEventListener, CommPortOwnershipListener
{
/*
* Instance Object Logger
*/
private static Logger logger = Logger.getLogger(Sms.class);

/*
* Constance status
*/
public static final int SC_OK = 0;
public static final int SC_ERROR = 1;
public static final int SC_PDU_PARSE_ERROR = 2;

/*
* Flux I/O
*/
private OutputStream outStream;
private InputStream inStream;

/*
* Read incoming SMS from SIM
*/
public IncomingSms rx_sms = null;

/*
* Config Serial Port
*/
private SerialParameters parameters;

/*
* Communication scan port
*/
private CommPortIdentifier portId;

/*
* Communication in serial port
*/
private SerialPort sPort;

/*
* Status comm port
*/
public int portStatus = OK;
private static Boolean portStatusLock = new Boolean(true);
private boolean POLLING_FLAG;
private String portStatusMsg = "";

/*
* Type of response
*/
private static final int OK = 1;
private static final int WAIT = 2;
private static final int ERROR = 3;
private static final int WMSG = 4;
private static final int RMSG = 5;
private static final int ECHO = 6;
private static final int TIMEOUT = 7;

/*
* Buffer serial incoming event
*/
private byte[] readBuffer = new byte[20000];
private int bufferOffset = 0; // serialEvent

/*
* LF CR
*/
private static final String lfcr = "\r\n";

/*
* Default index memory is 1
*/
private int indexCurrentMemory = 1;

/*
* Default memory is "SM"
*/
private String currentMemory = "\"SM\"";

/**
* Constructor!
*
* @param parameters
*/
public Sms(SerialParameters parameters)
{
this.parameters = parameters;
}

/**
* Initialize driver to be able to connect to serial port
* incase application is running from Windows
* as u might expect no driver initialization is required on linux
* ensure you initialize only once on Windows so as to avoid multiple port enumeration
*
* @return String "successful" or "failure"
*/
public String initializeWinDrivers()
{
String drivername = "com.sun.comm.Win32Driver";
try
{
CommDriver driver = (CommDriver) Class.forName(drivername).newInstance();
driver.initialize();
return "successful";
}
catch (Throwable th)
{
// Discard it
return "failure";
}
}

/**
* Return type of serial port (depend type of driver!) Driver=com.sun.comm.Win32Driver (window)
* Driver=gnu.io.RXTXCommDriver (all platform)
*
* @param portType
* @return String with driver type
*/
static String getPortTypeName(int portType)
{
// we use on window...
switch (portType)
{
case CommPortIdentifier.PORT_PARALLEL :
return "Parallel";
case CommPortIdentifier.PORT_SERIAL :
return "Serial";
default :
return "unknown type";
}
}

/**
* Open serial connection with COM port
*
* @param _port
* @throws IOException
*/
public void openConnection(String _port) throws IOException
{
openConnection(_port, null);
}

/**
* Open serial connection with COM port
*
* @param _port
* @param _pinNumber
* @throws IOException
*/
public void openConnection(String _port, String _pinNumber) throws IOException
{
String port = _port;
if (_port == null) port = parameters.getPortName();

// Obtain a CommPortIdentifier object for the port you want to open.
try
{
portId = CommPortIdentifier.getPortIdentifier(port);
}
catch (NoSuchPortException e)
{
e.printStackTrace();
throw new IOException(e.getMessage());
}

// Open the port represented by the CommPortIdentifier object. Give
// the open call a relatively long timeout of 30 seconds to allow
// a different application to relinquish the port if the user
// wants to.
try
{
sPort = (SerialPort) portId.open("MobileAccess", 5000);
}
catch (PortInUseException e)
{
throw new IOException(e.getMessage());
}

// Set the parameters of the connection. If they won't set, close the
// port before throwing an exception.
try
{
setConnectionParameters();
}
catch (IOException e)
{
sPort.close();
throw e;
}

// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
try
{
outStream = sPort.getOutputStream();
inStream = sPort.getInputStream();
}
catch (IOException e)
{
sPort.close();
throw new IOException("Error opening i/o streams");
}
// Add this object as an event listener for the serial port.
try
{
sPort.addEventListener(this);
}
catch (TooManyListenersException e)
{
sPort.close();
throw new IOException("too many listeners added");
}

// Set notifyOnDataAvailable to true to allow event driven input.
sPort.notifyOnDataAvailable(true);

// Add ownership listener to allow ownership event handling.
portId.addPortOwnershipListener(this);

// init modem connection with pin number
initializeModem(_pinNumber);
}

/**
* Initialize modem with PIN number
*
* @param pinNumber
*/
private void initializeModem(String pinNumber)
{
atCmd("ATE0", 0, 1000); // turn off command echo
atCmd("AT+CMEE=2", 0, 500); // verbose all messages
atCmd("AT+CMGF=0", 0, 500); // set Pdu mode (default binary)
//atCmd("AT+CNMI=0,0,0,0", 0, 500);// disable indications -direct to TE?

if (pinNumber != null)
{
//enter pin number
atCmd("AT+CPIN=\"" + pinNumber + "\"", 0, 1000);
if (portStatus == ERROR)
{
logger.error("The pin number " + pinNumber + " is INCORRECT. Please try again.");
// close session!
this.close();
}
}
}

/**
* List open serial port
*
* @return Array String
*/
public String[] listPorts()
{
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
ArrayList portList = new ArrayList();
String portArray[] = null;
while (ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
if (port.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
portList.add(port.getName());
}
portArray = (String[]) portList.toArray(new String[0]);
}
return portArray;
}

/**
* Handles ownership events. If a PORT_OWNERSHIP_REQUESTED event is received a dialog box is created asking the user
* if they are willing to give up the port. No action is taken on other types of ownership events.
*/
public void ownershipChange(int type)
{
if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED)
{
logger.debug("PORT_OWNERSHIP_REQUESTED received : Your port has been requested by another application...");

this.close();
}
else if (type == CommPortOwnershipListener.PORT_OWNED)
{
logger.debug("PORT_OWNED received!");
}
else if (type == CommPortOwnershipListener.PORT_UNOWNED)
{
logger.debug("PORT_UNOWNED received!");
}
}

/**
* Sets the connection parameters to the setting in the parameters object. If set fails return the parameters object
* to original settings and throw exception.
*/
private void setConnectionParameters() throws IOException
{
// Save state of parameters before trying a set.
int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();

// Set connection parameters, if set fails return parameters object
// to original state.
try
{
sPort.setSerialPortParams(parameters.getBaudRate(), parameters.getDatabits(), parameters.getStopbits(),
parameters.getParity());
}
catch (UnsupportedCommOperationException e)
{
parameters.setBaudRate(oldBaudRate);
parameters.setDatabits(oldDatabits);
parameters.setStopbits(oldStopbits);
parameters.setParity(oldParity);
parameters.setFlowControlIn(oldFlowControl);
parameters.setFlowControlOut(oldFlowControl);
throw new IOException("Unsupported parameter");
}
// Set flow control.
try
{
sPort.setFlowControlMode(parameters.getFlowControlIn() | parameters.getFlowControlOut());
sPort.enableReceiveThreshold(1);
sPort.enableReceiveTimeout(2000); // timeout 2s ?!
}
catch (UnsupportedCommOperationException e)
{
throw new IOException("Unsupported flow control");
}
}

// To be used to send AT command via the IR/serial link to the mobile
// device (for standard AT commands use mode=0)
private synchronized int atCmd(String cmd, int mode, int timeout)
3
Rock
 
aquí
para poder enviar un sms, es necesario realizar un programa que envíe sms a través del módem de un teléfono móvil, para ello hay que saber comunicarse por un puerto serie, "la commAPI de sun por ejemplo que es una buena base si el programa está en java" y también conocer bien los comandos AT.
para enviar el sms siempre necesitarás un teléfono con una suscripción, y el sms se descontará de tu tarifa "el precio de un sms"
1
projet_j2me Mensajes publicados 4 Estado Miembro
 
¿Podrías informarme, por favor, sobre los pasos que hay que seguir para certificar su aplicación?
Gracias.
mi correo electrónico ==> ABD_EST@hotmail.fr
0
Canard007 Mensajes publicados 5954 Fecha de registro   Estado Colaborador 216
 
segunda solución pasar por un sitio web que ofrezca el envío de sms gratis.
Sin embargo, será necesario verificar que no rastreen los robots.
--
¡Por favor, inserte MONEDA!
1
sabi
 
hola
1
John
 
Buenas noches a todos,
aparentemente este sitio ofrece lo que todo el mundo busca desesperadamente
http://mmsgratuit.c.la
0
tck-lt
 
Hola,

en el marco de mi primera pasantía, utilicé una API existente en SourceForge llamada jSMSEngine. Contiene las clases necesarias para la recepción y el envío de SMS a través de un directorio. La probé y funciona correctamente, aunque la configuración del puerto correcto a veces es laboriosa.
-1
projet_j2me Mensajes publicados 4 Estado Miembro
 
Lo siento, no puedo enviar mi código fuente.
0
ingenioura > projet_j2me Mensajes publicados 4 Estado Miembro
 
Buenas noches,
tengo una aplicación similar a la suya para el envío de SMS utilizando Java, ¿puede enviarme su código? Gracias.
0
Baleb
 
¿Dónde está? Ya publica el tuyo.
0
levantcommentcamarche Mensajes publicados 1 Estado Miembro
 
Désolé, je ne peux pas vous aider avec ça.
0
iso03
 
Hola a todos, también necesitaría el código fuente si es posible, estoy trabajando en una aplicación del mismo tipo. Aquí está mi correo: ***@***. ¡Gracias de antemano!
0
freto Mensajes publicados 1543 Fecha de registro   Estado Miembro Última intervención   165
 
En este caso, hay que indicar la ruta de esos paquetes en el classpath... no sabía que existía el paquete comm, pensé que era un error de sintaxis... todo el mundo puede equivocarse xD
Para indicar la ruta en el classpath, puedes configurar la variable de entorno $CLASSPATH, o al compilar indicas con --classpath:ruta_al_paquete.
0
Dookstyle
 
Hola a todos, aquí está la aplicación en cuestión
necesita una conexión a internet
La utilizo en mi PocketPC y funciona perfectamente

Vía WIFI (GRATUITO) o en ausencia de la misma, en 3G o GPRS -->
Costo de conexión no --> nada ventajoso



celity freeSMS

yo como único
nosotros como unión

chao Dookstyle
0
mhaido
 
hola
¿dónde está tu aplicación?
0
mimi
 
Hola a todos, soy Imene de Argelia "Relizane" y me gustaría saber cómo votar, y mando un gran saludo a Amel B y a todos los candidatos.
-1
salah23 Mensajes publicados 1 Estado Miembro
 

Hola a todos, soy Salah de Annaba, este año hay que sacar el BAC, si no, ¡alhaca! ¡Viva Cerdeña!

-1
freto Mensajes publicados 1543 Fecha de registro   Estado Miembro Última intervención   165
 
¿Nos estamos alejando del tema, ¿verdad?
-1
bouzid
 
Bouzid, Naouel y Hanane de Dellys votan por Amel Bouchoucha.
-1
freto Mensajes publicados 1543 Fecha de registro   Estado Miembro Última intervención   165
 
Primera error: se escribe con una sola m.
Y necesitas instalar los paquetes log4j.
-1
FatalError404
 
no, está correcto, hay una API "java COMM" que se encarga de hacer una conexión con puerto serie y puerto paralelo.
Entonces hay que importar javax.comm.*;
Gracias
0
lg2006 Mensajes publicados 12 Fecha de registro   Estado Miembro 3 > FatalError404
 
En realidad, no consigo configurar los paquetes como javax.com o el paquete RMI. Gracias de antemano por ayudarme.
0