Sending Email in Android using JavaMail API without using mailing APP - android

Sending Email in Android using JavaMail API without using the default/built-in app
Using this tutorial, I've loaded up the code into a sample android project and imported the libraries. Changed the parameters in the lines:
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
GMailSender sender = new GMailSender("sender#gmail.com", "sender_password");
sender.sendMail("This is Subject", "This is Body", "sender#gmail.com", "recipient#gmail.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
Wanted to test it out and in this code, the try block of code gets executed successfully when I press the button, but I don't receive the mail, nor do I get any errors. Since there's no readme or any guidelines as to how to use this code, I have no choice but to ask what I'm doing wrong.
Just to clear the confusion, I've put the senders email instead of sender#gmail.com, same goes for password and recipient#gmail.com.
I've also added the INTERNET permission to the manifest.

If you want to use mailgun instead you can do it like this:
public void sendEmailInBackground(final String subject, final String body, final String... toAddress) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
String hostname = "smpt.mailgun.org";
int port = 25;
String login = "login";
String password = "password";
String from = "from#example.com";
AuthenticatingSMTPClient client = null;
try {
client = new AuthenticatingSMTPClient();
// optionally set a timeout to have a faster feedback on errors
client.setDefaultTimeout(10 * 1000);
// you connect to the SMTP server
client.connect(hostname, port);
// you say helo and you specify the host you are connecting from, could be anything
client.ehlo("localhost");
// if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done here
if (client.execTLS()) {
client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
checkReply(client);
client.setSender(from);
checkReply(client);
String address = "";
if (toAddress != null) {
for (String to : toAddress) {
if(to != null && to.length() > 0) {
client.addRecipient(to);
if (address.length() == 0) {
address += ",";
}
address += to;
}
}
}
if(address.length() == 0){
logger.warning("No address specified for mail message");
return null;
}
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null) {
SimpleSMTPHeader header = new SimpleSMTPHeader(from, address, subject);
writer.write(header.toString());
writer.write(body);
writer.close();
if (!client.completePendingCommand()) {// failure
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("STARTTLS was not accepted " + client.getReply() + client.getReplyString());
}
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
logger.severe("Error sending email",e);
} finally {
if (client != null) {
try {
client.logout();
client.disconnect();
} catch (Exception e) {
logger.warning("Error closing email client: " + e.getMessage());
}
}
}
return null;
}
};
task.execute();
}
private static void checkReply(SMTPClient sc) throws IOException {
if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
throw new IOException("Transient SMTP error " + sc.getReplyString());
} else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
throw new IOException("Permanent SMTP error " + sc.getReplyString());
}
}

Related

How to know Incoming Email Message ID to get message contents

I want to get Incoming Email Message ID for get message contents. I've applied this code to listen change in message counts.
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
System.out.println("Message Count Event Fired");
}
public void messagesRemoved(MessageCountEvent e) {
System.out.println("Message Removed Event fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
System.out.println("Message Changed Event fired");
}
});
the above code works fine for IMAP server, whenever a message added or removed. But i want to know which Message has been removed or Added.
Kindly help. the full code is,
MainActivity:
String host = "imap.gmail.com";
String mailStoreType = "imap";
String username = "EmailAddress#gmail.com";
String password = "****";
CheckingMails.check(host, mailStoreType, username, password);
CheckingMails:
public class CheckingMails {
public static void check(String host, String storeType, String user,
String password) {
boolean supportsIdle = false;
IMAPFolder folder = null;
int freq = 2000;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
final javax.mail.Store store = session.getStore("imaps");
store.connect(host, user, password);
folder = (IMAPFolder) store.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
Log.d("fhjg43524318778", folder.toString());
try {
folder = (IMAPFolder) store.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
SearchTerm sender = new FromTerm(new InternetAddress("zohaibsvu#gmail.com"));
// Getting from specific email
Message[] message = folder.search(sender);
Log.d("fghjgh564", String.valueOf(message.length));
for (int i = 1; i < message.length; i++) {
Message writePart = message[i];
int id = message[i].getMessageNumber();
String from = message[i].getFrom()[0].toString();
String subject = message[i].getSubject();
Log.d("dfgh3423", "# "+id+" From "+from+", subject "+subject);
}
} catch (AddressException y) {
} catch (MessagingException u) {
}
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
public void messagesRemoved(MessageCountEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
Log.d("asfd3565678", "Message Count Event Fired");
}
});
// Check mail once in "freq" MILLIseconds
int freq = 2000;
boolean supportsIdle = false;
try {
if (emailFolder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) emailFolder;
f.idle();
supportsIdle = true;
}
} catch (FolderClosedException fex) {
throw fex;
} catch (MessagingException mex) {
supportsIdle = false;
}
for (; ; ) {
if (supportsIdle && emailFolder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) emailFolder;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(freq); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
emailFolder.getMessageCount();
}
}
/*
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
*/
//close the store and folder objects
// emailFolder.close(false);
// store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Message-ID is accessible via the MimeMessage.getMessageID method.
If you were really asking about the IMAP UID, that's accessible via the UIDFolder.getUID method. Cast the Folder object to UIDFolder.

asp.net web forms gives error in mobile browsers

I have a asp.net web forms site which runs well in PC. However when I try to access it from mobile it gives an object reference error. The site is asp.net 4.5.1 and used normal asp.net server controls.
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoginView lView = (LoginView)this.Master.FindControl("LoginView1");
lView.Visible = false;
if (Request.QueryString["exp"] != null)
{
string msg = "Session expired please login.";
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "$(function() { LoginFail('" + msg + "'); });", true);
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
ManchesterContext context = new ManchesterContext();
if (Membership.ValidateUser(txtUserId.Text, txtPassword.Text))
{
MembershipUser user = Membership.GetUser(txtUserId.Text);
aspnet_Users dbUser = context.aspnet_Users.Where(u => u.UserName.Equals(user.UserName)).FirstOrDefault();
if (dbUser.PassUpdated)//This means user has already changed default password. Perform login.
{
SetAuthenticationCookie(user);
aspnet_Users dbEntry = context.aspnet_Users.Where(u => u.UserName == user.UserName).FirstOrDefault();
SessionInfo.InitSession(dbEntry.UserId, dbEntry.UserName);
Session.Add("USR_KEY", dbEntry.UserId);
FormsAuthentication.RedirectFromLoginPage(user.UserName,false);
}
else //User has not updated default password.
{
Session.Add("TEMP_USR", txtUserId.Text);
Session.Add("TEMP_PASS", txtPassword.Text);
Response.Redirect("ChangePassword.aspx");
}
}
else
{
string msg = "Invalid User Id or Password.";
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "$(function() { LoginFail('" + msg + "'); });", true);
}
}
public void SetAuthenticationCookie(MembershipUser user)
{
Response.Cookies.Clear();
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
{
Expires = System.DateTime.Now.AddDays(-1),
HttpOnly = true
};
HttpContext.Current.Response.Cookies.Add(cookie);
return;
}
}

How to send SIP messages using pjsua2 android

I am trying to send messages with pjsua2. But it is throwing a exception. Please suggest me.
Here is my code
public void sendInstantMessage(String buddy_uri) {
buddy_uri = "sip:aaaaa#xxx.yyyyyy.zzz";
BuddyConfig cfg = new BuddyConfig();
cfg.setUri(buddy_uri);
cfg.setSubscribe(true);
MyBuddy im = new MyBuddy(cfg);
SendInstantMessageParam prm = new SendInstantMessageParam();
prm.setContent("Hi This is X, sending message");
boolean valid = im.isValid();
Log.e(TAG, "valid ======= "+valid);
try {
im.sendInstantMessage(prm);
} catch (Exception e) {
Log.e(TAG, "sendInstantMessage ==== "+e);
e.printStackTrace();
return;
}
}
It throwing a exception and here is log
05-27 15:42:40.705: E/SipApi(27611): valid ======= false
05-27 15:42:40.706: A/libc(27611): ../src/pjsua-lib/pjsua_pres.c:231: pjsua_buddy_get_info: assertion "pjsua_buddy_is_valid(buddy_id)" failed
Finally I got the solution for sending SMS using pjsip-2.4
Here is the code
/**Send message to this number
* #param String number
* #param String msgBody*/
public void sendInstantMessage(String number, String msgBody) {
String sipServer = "aaa.ggg.net";
String buddy_uri = "<sip:" + number + "#" + sipServer + ">";
BuddyConfig bCfg = new BuddyConfig();
bCfg.setUri(buddy_uri);
bCfg.setSubscribe(false);
MyBuddy myBuddy = new MyBuddy(bCfg);
SendInstantMessageParam prm = new SendInstantMessageParam();
prm.setContent(msgBody);
try {
myBuddy.create(account, bCfg);
myBuddy.sendInstantMessage(prm);
myBuddy.delete();
} catch (Exception e) {
e.printStackTrace();
return;
}
}

GCM: MulticastResult - which result is from which device?

Following the last section in the GCM: Getting Started guide, there's some book-keeping to be done after receiving the results.
Quoting from the guide:
It's now necessary to parse the result and take the proper action in the following cases:
If the message was created but the result returned a canonical registration ID, it's necessary to replace the current registration
ID with the canonical one.
If the returned error is NotRegistered, it's necessary to remove that registration ID, because the application was uninstalled from
the device.
Here's a code snippet that handles these 2 conditions:
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
}
}
The guide above refers to a single result, and not to the multicast case.
I'm not sure how to handle the multicast case:
ArrayList<String> devices = new ArrayList<String>();
for (String d : relevantDevices) {
devices.add(d);
}
Sender sender = new Sender(myApiKey);
Message message = new Message.Builder().addData("hello", "world").build();
try {
MulticastResult result = sender.send(message, devices, 5);
for (Result r : result.getResults()) {
if (r.getMessageId() != null) {
String canonicalRegId = r.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
// BUT WHICH DEVICE IS IT?
}
} else {
String error = r.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
// BUT WHICH DEVICE IS IT?
}
}
}
} catch (IOException ex) {
Log.err(TAG, "sending message failed", ex);
}
I submit a list of devices, and receive back a list of results.
The Result object doesn't contain the registration id, but only a canonical id if the first is obsolete.
It is undocumented if the two lists are co-related (ie. preserves order and size).
How can I be sure which result refer to which device?
-- UPDATE
I've pasted a snippet of the solution in a separate answer below
The results are in the order of your registration_id array that you sent to GCM server. e.g. if your registration_ids are:
[id1, id4, id7, id8]
Then the results array you get will have same order for id1, id4, id7, and id8.
You just need to parse each result accordingly, e.g. if the 2nd result has 'message_id' and 'registration_id' of 'id9', you know 'id4' is now obsolete and should be replaced by id9.
For the readers convenience, here is a snippet that handles response for multiple devices
public void sendMessageToMultipleDevices(String key, String value, ArrayList<String> devices) {
Sender sender = new Sender(myApiKey);
Message message = new Message.Builder().addData(key, value).build();
try {
MulticastResult result = sender.send(message, devices, 5);
MTLog.info(TAG, "result " + result.toString());
for (int i = 0; i < result.getTotal(); i++) {
Result r = result.getResults().get(i);
if (r.getMessageId() != null) {
String canonicalRegId = r.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// devices.get(i) has more than on registration ID: update database
}
} else {
String error = r.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from devices.get(i) - unregister database
}
}
}
} catch (IOException ex) {
MTLog.err(TAG, "sending message failed", ex);
}
}
This solution is done by google developer sample GCM Demo application
note the asyncSend for multicasting handle
List<GcmUsers> devices=SearchRegisterdDevicesByCourseCommand.execute(instructorId, courseId);
String status;
if ( devices.equals(Collections.<GcmUsers>emptyList())) {
status = "Message ignored as there is no device registered!";
} else {
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
GcmUsers gcmUsers = devices.get(0);
Message message = new Message.Builder().build();
Result result = sender.send(message, gcmUsers.getGcmRegid(), 5);
status = "Sent message to one device: " + result;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (GcmUsers device : devices) {
counter++;
partialDevices.add(device.getGcmRegid());
int partialSize = partialDevices.size();
if (partialSize == MULTICAST_SIZE || counter == total) {
asyncSend(partialDevices);
partialDevices.clear();
tasks++;
}
}
status = "Asynchronously sending " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
private void asyncSend(List<String> partialDevices) {
// make a copy
final List<String> devices = new ArrayList<String>(partialDevices);
threadPool.execute(new Runnable() {
public void run() {
Message message = new Message.Builder().build();
MulticastResult multicastResult;
try {
multicastResult = sender.send(message, devices, 5);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error posting messages", e);
return;
}
List<Result> results = multicastResult.getResults();
// analyze the results
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logger.fine("Succesfully sent message to device: " + regId +
"; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.info("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
logger.info("Unregistered device: " + regId);
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to " + regId + ": " + error);
}
}
}
}});
}

Having a bit of trouble tcp connecting in Android Client

This might be a complex problem with my application but I'll do my best to describe it as accurately as I can.
I am making an Android Client and making use of a couple of helper classes someone else handed to me at work. The helper Android classes are called TcpClient.java and PVDCAndroidClient.java. PVDCAndroidClient.java makes use out of the TcpCLient, using a tcpCLient object to connect via serverIP and port.
Here is PVDCAndroidClient.java:
public class PVDCAndroidClient {
// constants
public static final String DEFAULT_LOGIN_URI = "http://me.net:8000/";
private TcpClient tcpClient = null;
private UdpClient udpClient = null;
private boolean connected = false;
private boolean loggedin = false;
private static SimpleDateFormat sdf;
private String loginURI = DEFAULT_LOGIN_URI;
private int getUserNumber;
TcpMessageListener listener = null;
/**
* Connects to proxy server, blocks until complete or timeout
* #param serverIP
* #param port
*/
public void connect(String serverIP, int port)
{
try
{
if(serverIP.length() != 0 && port != 0)
{
tcpClient = new TcpClient();
tcpClient.addTcpListener(listener);
tcpClient.connect(serverIP, port);
}
}
catch(Exception e)
{
e.printStackTrace();
Log.d("Could not connect to server, possbile timeout...", "error");
}
}
///// Make login function a blocking call
// Default login, use last location as login location
public boolean login(String fName, String lName, String password)
{
return this.login(fName, lName, password, "last location");
}
public boolean login(String fName, String lName, String password, String region)
{
return this.login(fName, lName, password, "last location", 128, 128, 20);
}
public boolean login(String fName, String lName, String password, String region, int loginX, int loginY, int loginZ)
{ sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Check passed values
// x, y and z should be between [0, 256]
// strings should not be null or empty(except lName which can be empty)
if((loginX >= 0 && loginX <= 256) && (loginY >=0 && loginY <= 256) && (loginZ >= 0 && loginZ <= 256))
{
if(fName.length() != 0 && fName != null)
{
// Construct packet xml structure
// Send request and wait until reply or timeout
// return false if timeout (or throw exception?)
// if not timeout, read result packet and determine return value
// getUserNumber = tcpClient.getUserNum();
StringWriter stringWriter = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(stringWriter);
// Indentation is not required, but helps with reading
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
// TODO: Remove hardcoding of strings, make either constants or place in strings.xml
// TODO: Move the header construction to other method as it is fairly constant other than request num and no need to repeat that much code
serializer.startTag("", "pvdc_pkt");
serializer.startTag("", "pvdc_header");
// TODO: replace this with a string unique to the system
serializer.startTag("", "ID");
serializer.text("838393djdjdjd");
serializer.endTag("", "ID");
// TODO: replace this with actual user number from server
serializer.startTag("", "user_num");
serializer.text("22");//get userNum from above
serializer.endTag("", "user_num");
// TODO: add a request number counter to increment this on each request
serializer.startTag("", "request_num");
serializer.text("1");
serializer.endTag("", "request_num");
serializer.startTag("", "DateTime");
serializer.text(sdf.toString()); //utc time variable.
serializer.endTag("", "DateTime");
serializer.endTag("", "pvdc_header");
serializer.startTag("", "pvdc_content");
serializer.attribute("", "type", "requestlogin");
serializer.startTag("", "name");
serializer.attribute("", "fname", fName);
serializer.attribute("", "lname", lName);
serializer.endTag("", "name");
serializer.startTag("", "password");
serializer.text(password);
serializer.endTag("", "password");
serializer.startTag("", "server");
serializer.text(this.loginURI);
serializer.endTag("", "server");
serializer.startTag("", "location");
serializer.attribute("", "region", region);
serializer.text(loginX + ";" + loginY +";" + loginZ);
serializer.endTag("", "location");
serializer.endTag("", "pvdc_content");
serializer.endTag("", "pvdc_pkt");
// Finish writing
serializer.endDocument();
// write xml data out
serializer.flush();
//
sendLogin(stringWriter);
} catch (Exception e) {
Log.e("Exception", "error occurred while creating xml file");
return false;
}
// Print out xml for debugging
Log.d("PVDCAndroidClient Login", stringWriter.toString().trim());
}
else
{
Log.d("Error in name checking", "fName either blank or null");
}
}
else
{
Log.d("login coordinates X,Y, or Z not between 0-256", "Coordinates Error");
}
return true;
}
// moveString should contain the properly formatted movement command(s)[see above move request description]
public void sendLogin(StringWriter stringWriter)
{
tcpClient.sendMessage(stringWriter.toString());
}
}
Here is the actual TcpClient.java:
public class TcpClient {
public interface TcpMessageListener{
public void onMessage(TcpClient client, String message);
}
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private Thread listenThread = null;
private boolean listening = false;
private int userNum = -1;
private List<TcpMessageListener> listeners = new ArrayList<TcpMessageListener>();
public int getUserNum()
{
return this.userNum;
}
public TcpClient() {
}
public void addTcpListener(TcpMessageListener listener)
{
synchronized(this.listeners)
{
this.listeners.add(listener);
}
}
public void removeTcpListener(TcpMessageListener listener)
{
synchronized(this.listeners)
{
this.listeners.remove(listener);
}
}
public boolean connect(String serverIpOrHost, int port) {
try {
socket = new Socket(serverIpOrHost, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.listenThread = new Thread(new Runnable(){
public void run() {
int charsRead = 0;
char[] buff = new char[4096];
while(listening && charsRead >= 0)
{
try {
charsRead = in.read(buff);
if(charsRead > 0)
{
Log.d("TCPClient",new String(buff).trim());
String input = new String(buff).trim();
synchronized(listeners)
{
for(TcpMessageListener l : listeners){
l.onMessage(TcpClient.this, input);
}
}
if (input.toLowerCase().contains("<user_num>")){
int index = input.toLowerCase().indexOf("<user_num>");
index += "<user_num>".length();
int index2 = input.toLowerCase().indexOf("</user_num>");
userNum = Integer.parseInt(input.substring(index, index2));
}
}
} catch (IOException e) {
Log.e("TCPClient", "IOException while reading input stream");
listening = false;
}
}
}
});
this.listening = true;
this.listenThread.setDaemon(true);
this.listenThread.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
return false;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
return false;
} catch (Exception e) {
System.err.println(e.getMessage().toString());
return false;
}
return true;
}
public void sendMessage(String msg) {
if(out != null)
{
out.println(msg);
out.flush();
}
}
public void disconnect() {
try {
if(out != null){
out.close();
out = null;
}
if(in != null){
in.close();
in = null;
}
if (socket != null) {
socket.close();
socket = null;
}
if(this.listenThread != null){
this.listening = false;
this.listenThread.interrupt();
}
this.userNum = -1;
} catch (IOException ioe) {
System.err.println("I/O error in closing connection.");
}
}
}
LASTLY, here is what I have been coding today and cannot seem to get this to work. I don't get any blatant exceptions, just a warning on Logcat, that says, "Couldn't get I/O for the connection".
public class AndroidClientCompnt extends Activity {
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptPassLoginActivity;
private String getIpAddressSharedPrefs;
private String getPassword, getName, getRegionSelect, getGridSelect;
private String fName, lName;
private SharedPreferences settings;
private boolean resultCheck = false;
private int portNum;
PVDCAndroidClient client;
private String name;
private CharSequence[] getView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Intent intent = getIntent();
// getting object's properties from LoginActivity class.
getName = intent.getStringExtra("name");
getPassword = intent.getStringExtra("password");
getRegionSelect = intent.getStringExtra("regionSelect");
getGridSelect = intent.getStringExtra("gridSelect");
Log.d("VARIABLES", "getName = " + getName + "getPassword" + getPassword
+ "getRegionSelect = " + getRegionSelect + ".");
setResult(Activity.RESULT_CANCELED);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
// grid selected as well? sometime?
settings = PreferenceManager.getDefaultSharedPreferences(this);
getIpAddressSharedPrefs = settings.getString(IP_ADDRESS_SHARED_PREFS,
"");
portNum = Integer.parseInt(settings.getString(PORT_SHARED_PREFS, ""));
Log.d("SHARED" + getIpAddressSharedPrefs + "port " + portNum, "");
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
try {
// first connect attempt.
client.connect(getIpAddressSharedPrefs, portNum);
resultCheck = client.isConnected();
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not connect.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Ip preference and port blank", Toast.LENGTH_LONG).show();
}
finish();
}
private class UploadTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
// encrypting user's password with Md5Hash class.
try {
encryptPassLoginActivity = MdHashing
.MD5(getPassword.toString());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (resultCheck == true) {
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = name.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,
getRegionSelect, 128, 128, 20);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent goToInWorld = new Intent(
AndroidClientCompnt.this.getApplicationContext(),
PocketVDCActivity.class);
startActivity(goToInWorld);
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
I know this is a super long post and I am asking a lot but if anyone could take a look at this I would very much appreciate it. I've been at this all day, trying to make use of these helper classes I got and can't get it to work. It also doesn't help that I'm not too experienced in this client/server stuff. Any nudges in the right direction or an accepted solution would REALLY mean something to me.
Thank you kindly,
Have a good evening.
Can you post your manifest?
You may need to add the following :
<uses-permission android:name="android.permission.INTERNET"/>
Additionally - I assume you see nothing ever happen on the server side of this connection?
1) Make sure you have the following permission in your Android-Manifest file:
<uses-permission android:name="android.permission.INTERNET/>
w/o this you definitely won't be making any tcp/ip connections.
2) You will want to run the code in debug mode, and place breakpoints where the connection information
is set and also what results are at several points. In other words you need to dig deeper.
If you are somewhat new to coding there is no better investment of time than in running the debugger and stepping line by line through the code. Code only comes to life inside a debugger, where you can see the values of variables and results. So set several breakpoints, step through and you will see more. It is more difficult to debug where there are threads however.

Categories

Resources