Want to create a background android service that will continuously check the incoming emails. I have create an activity and there is an start and stop service button along with some input fields from user. On start service button click, I call the onStartCommand() service method and send the required details (email id, pwd etc) from activity to service via intent of service. Now, as I have to login in an email account in onStartCommand() I called Store.connect() method which is throwing an exception android.os.networkonmainthreadexception. I searched and found that I have to do the connect the email account tasks in Asynctask's doinbackground method so that main thread do not get disturbed. So, I did the same but even there I am getting the same error. But when I did the same thing in activity by making the async inner class then it is working fine but not in case of service.
Here is onstartcommand() method
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
super.onStartCommand(intent, flags, startId);
String resp = null;
if(intent !=null && intent.getExtras() != null){
emailID = intent.getExtras().getString("email");
pwd = intent.getExtras().getString("pwd");
urlServer = intent.getExtras().getString("urlServer");
from_whom = intent.getExtras().getString("from_whom");
AsyncTaskRunner runner = new AsyncTaskRunner();
//runner.execute(emailID, pwd, urlServer);
resp = runner.doInBackground(emailID, pwd, urlServer);
}
if ((resp.equalsIgnoreCase("yes")))
{
startTimer();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
return START_STICKY;
and private inner asynctask class
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
@Override
protected String doInBackground(String... params) {
try {
//emailManager = new EmailManager(params[0], params[1], params[2], "smtp.gmail.com", "imap.gmail.com");
emailManager = new EmailManager("test2891test", "Testing2891!", "gmail.com", "smtp.gmail.com", "imap.gmail.com");
Message[] emails = emailManager.getMails();
Message latest_email = emails[emails.length -1]; // latest email
email_from = InternetAddress.toString(latest_email.getFrom());
email_sub = latest_email.getSubject();
Multipart mp = (Multipart) latest_email.getContent();
getting error android.os.networkonmainthreadexception in emailmanager.getmails() method for store.connect():
public Message[] getMails() throws MessagingException {
store = imapSession.getStore("imaps");
store.connect(mailServer, account.emailAddress, account.password);
inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message[] result = inbox.getMessages();
return result;
}
IF I WILL DO ALL THESE ASYNCTASK IN ACTIVITY THEN IT IS WORKING FINE BUT RAISING THE ERROR IN CASE OF SERVICE.
ANY HELP WOULD BE WELL APPRECIATED.
THANKS