简体   繁体   中英

android asyncTask mail attachment send error

I have problem AsyncTask such that it is working in android version 4.4 or above but not in 4.0

for mailing i use

public class Mailing   {

    Message message;
    Properties props;

    String ss,file,locationpre="\"https://www.google.com/maps/@";

    Context c;

    Mailing(Context context)
    {
        c=context;
    }
    public void sending(String s)
    {
        final LocationManager locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
        file=s;
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                locationpre=locationpre+location.getLatitude()+","+location.getLongitude()+",12z";
                ss="Lat : "+location.getLatitude()+" , Long : "+location.getLongitude();

                Log.d("lat",""+location.getLatitude());

            }

            public void onStatusChanged(String provider, int status, Bundle extras) {}

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}
        };

        // Register the listener with the Location Manager to receive location updates
        try {


            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }






        new Thread(new Runnable() {
            @Override
            public void run() {
                try {


                    new SendMail().execute();


                } catch (Exception e) {
                    Log.e("SendMail", e.getMessage(), e);
                }
            }
        }).start();






    }



    public class SendMail extends AsyncTask<Void,Void,Void>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }

        @Override
        protected Void doInBackground(Void... params) {


            final String username = "iamzeus07";
            final String password = "sumanthkumar";

            props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");
            Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            message = new MimeMessage(session);
            try {
                String rrr="https://www.google.com/maps/@-15.623037,18.388672,12z";
                message.setFrom(new InternetAddress("iamzeus07@gmail.com"));
                message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("kishlayrajiem@gmail.com"));

                message.setSubject("URGENT XYZ IS IN DANGER");
                BodyPart bodyPart1 = new MimeBodyPart();
                bodyPart1.setText("HER location : " + locationpre+"    and  "+ss);
                BodyPart bodyPart2 = new MimeBodyPart();
                Log.d("mail", "part 1");
                String filename = file;





                DataSource source = new FileDataSource(filename);
                bodyPart2.setDataHandler(new DataHandler(source));
                bodyPart2.setFileName(filename);



                Log.d("mail", "part 2");
                message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");
                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(bodyPart1);
                multipart.addBodyPart(bodyPart2);
                Log.d("mail", "part 3");
                message.setContent(multipart);
                Log.d("mail", "part 4");
                Transport.send(message);
                Log.d("mail", "part 5");
            }
            catch (Exception e)
            {
                Log.d("mail","Unsuccessful");
                e.printStackTrace();
            }


            return null;
        }
    }

}

and the logcat says

11-22 23:34:20.029 24637-25096/github.bewantbe.screamDetector W/dalvikvm: Exception Ljava/lang/RuntimeException; thrown while initializing Landroid/os/AsyncTask;

11-22 23:34:20.029 24637-25096/github.bewantbe.screamDetector W/dalvikvm: threadid=12: thread exiting with uncaught exception (group=0x2b542210)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime: FATAL EXCEPTION: Thread-1132
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime: java.lang.ExceptionInInitializerError
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at github.bewantbe.screamDetector.Mailing$2.run(Mailing.java:101)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:  Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at android.os.Handler.<init>(Handler.java:121)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at android.os.AsyncTask.<clinit>(AsyncTask.java:190)
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at github.bewantbe.screamDetector.Mailing$2.run(Mailing.java:101) 
11-22 23:34:20.039 24637-25096/github.bewantbe.screamDetector E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856) 
11-22 23:34:20.219 24637-24637/github.bewantbe.screamDetector D/OpenGLRenderer: Flushing caches (mode 0)

AsyncTask s are called from the UI thread to perform background operations. So, creating a new thread to execute is giving you error.

Replace

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            new SendMail().execute();
        } catch (Exception e) {
            Log.e("SendMail", e.getMessage(), e);
        }
    }
}).start(); 

with

new SendMail().execute();

Let me know if this helps !

First, Here it says

execute(Params...) must be invoked on the UI thread.

Second, as doInBackground runs on new thread, the thread's looper must be handled right, check this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM