-1

Hello Friends I am new in android. I am developing one application of Daily Report.in this application i want to send an Email automatically in every 24 hours to user. i found how t send email by using my application without Intent.but i could not get a solution that how to send an email in every 24 hours please help me..

public class SendAttachment
            {
                public static void main()
                {
                        String to="emailaddress";
                        final String user="emailaddress";//change accordingly
                        final String password="password";//change accordingly 
                        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
                        System.out.println("111111111111111111111111111111111111111111111111");
                        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
                        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
                        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
                        CommandMap.setDefaultCommandMap(mc); 
                         Properties properties = System.getProperties();
                         properties.put("mail.smtp.port", "465"); 
                         properties.put("mail.smtp.host", "smtp.gmail.com");
                           properties.put("mail.smtp.socketFactory.port", "465");
                           properties.put("mail.smtp.socketFactory.class",
                                   "javax.net.ssl.SSLSocketFactory");
                           properties.put("mail.smtp.auth", "true");
                           properties.put("mail.smtp.port", "465");

                           javax.mail.Session session=javax.mail.Session.getDefaultInstance(properties,new Authenticator() 
                           {
                               protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
                                   return new javax.mail.PasswordAuthentication(user, password);
                               }
                           });

                           try
                           { 
                               MimeMessage message = new MimeMessage(session);
                               message.setFrom(new InternetAddress(user));
                               message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
                               message.setSubject("text"); 
                               //3) create MimeBodyPart object and set your message content    
                               BodyPart messageBodyPart1 = new MimeBodyPart();
                               messageBodyPart1.setText("Daily ConstructionReport"); 
                               //4) create new MimeBodyPart object and set DataHandler object to this object    
                               MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                           //Location of file to be attached
                               String filename = Environment.getExternalStorageDirectory().getPath()+"/text/tedt_unu.pdf";//change accordingly
                               DataSource source = new FileDataSource(filename);
                               messageBodyPart2.setDataHandler(new DataHandler(source));
                               messageBodyPart2.setFileName("Report"); 
                               //5) create Multipart object and add MimeBodyPart objects to this object    
                               Multipart multipart = new MimeMultipart();
                               multipart.addBodyPart(messageBodyPart1);
                               multipart.addBodyPart(messageBodyPart2); 
                               //6) set the multiplart object to the message object
                               message.setContent(multipart); 
                               //7) send message 
                               Transport.send(message); 
                              System.out.println("MESSAGE SENT....");
                          }
                            catch (MessagingException ex)

                            {
                                ex.printStackTrace();
                            }
                   }
}

This is My Send Attachment class when i want to send email i had just call a method SendAttachment.main(). and now where i could put this method so that i can send an email in every 24 hours..

public class PollReceiver extends BroadcastReceiver 
{
        private static final int PERIOD=5000;

        @Override
        public void onReceive(Context ctxt, Intent i) 
        {
                  scheduleAlarms(ctxt);

         }

        static void scheduleAlarms(Context ctxt)
        {
            AlarmManagermgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
                        Intent i=new Intent(ctxt, ScheduledService.class);
                        PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
                        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
                                         SystemClock.elapsedRealtime() +               5000,PERIOD, pi);
                      }
                    }

This is my Intent service class

public class ScheduledService extends IntentService 
{
    public ScheduledService()
{
    super("ScheduledService");
}

@Override
protected void onHandleIntent(Intent intent) 
{
    SendAttachment.main();
    Log.d(getClass().getSimpleName(), "I ran!");
}

And this is MY Main Activity

CheckBox ch1=(CheckBox)findViewById(R.id.checkBox1);
stopService(new Intent(getApplicationContext(), ScheduledService.class));
ch1.setOnCheckedChangeListener(new OnCheckedChangeListener() 
{

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {
        // TODO Auto-generated method stub
        if(isChecked)
        {
            PollReceiver.scheduleAlarms(ScheduledServiceDemoActivity.this);
        }
        else
        {

        }
});
Dharmesh
  • 53
  • 6

3 Answers3

0

Look at this to activate the alarm :Android AlarmManager

And this is the code to send Email:

Intent email = new Intent (Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ "EmailTarget@gmail.com"});
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
email.putExtra(Intent.EXTRA_SUBJECT,"Your Subject ");
email.putExtra(Intent.EXTRA_TEXT,  "Your Text Message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client:"));

Hope that this is help.

Community
  • 1
  • 1
user2235615
  • 1,513
  • 3
  • 17
  • 37
0

Combine an AlarmManager with a BroadcastReceiver like this:

AlarmManager alarmManager = (AlarmManager) context
        .getSystemService(Context.ALARM_SERVICE);
Intent emailIntent = new Intent(context, EmailAlarmReceiver.class);
// use emailIntent.putExtra(key, value) to put extras like what email to send
PendingIntent emailAlarm = PendingIntent.getBroadcast(context, 0,
        emailIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long oneDay = 24 * 60 * 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC,
        System.currentTimeMillis() + oneDay, oneDay, emailAlarm);

The BroadcastReceiver:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // get extras from intent and send email
    }
}

Don't forget to put this in your manifest inside the application-tag:

<receiver android:name=".EmailAlarmReceiver" />
0101100101
  • 5,786
  • 6
  • 31
  • 55
  • hey buddy thank you for giving an answer i have try this but still i did not understand that where i can put my email code and so that it can be automatically send an email it gone be nice of you if you post a full code please and thanks again – Dharmesh Sep 18 '14 at 13:59
  • look i have declare my send Attachment activity and whenever i want to send email i just call that method.now where i have to declare that method so that i can send email in every 24 hours – Dharmesh Sep 18 '14 at 14:14
  • @Dharmesh Inside the BroadcastReceiver. – 0101100101 Sep 18 '14 at 14:24
  • i put that Alarm manager code inside the Button's click event.is that ok?? – Dharmesh Sep 18 '14 at 14:33
  • Please add everything you're trying to your question. Otherwise I have no idea where and why the nullpointer is thrown. – 0101100101 Sep 18 '14 at 15:14
  • 1
    Hey man Thanks for Help i got a solution by including an IntentService class.i can now able to send an Email in 24 every 24 Hours.but still i Have a problem. I have to send Email when i check a checkbox and when the checkbox i uncheck it Must not be send.right now it is send when the activity is called.. – Dharmesh Sep 19 '14 at 05:11
  • @Dharmesh That should be easy to solve. You can use SharedPreferences (call PreferenceManager.getDefaultSharedPreferences(context)) to save "true" under some key when the checkbox is checked and overwrite it with "false" when not. The Service can then read this value and send an email only if the value is true. – 0101100101 Sep 19 '14 at 12:15
  • How you can managment more alarms, with ? –  Jun 30 '15 at 10:19
0

Create a service, add the email part into it and then create a AlarmManager that triggers the service daily.

You are all set.

For the check box part:

If you want to send an email immediately when the checkbox is checked then here is what you need to do:

checkBox = (CheckBox)findViewById(R.id.checkBox);
checkBox.setOnClickListener(this);

@Override
public void onClick(View v) 
{
   if(v.getId() == checkBox.getId())
    {
        if (checkBox.isChecked() == true)
        {
            //send email immediately
            //add the reference to true to DB or sharedPreference
        }
        else
        {

        }
    }

 }

Example:

If you want to send the email through service later.

if you have stored the reference in DB/Shared Preference - get the value.

 boolean checkBox = db.getCheckbox()

 if (checkBox == true)
 {
   //sendEmail
 }
 else
 {
  //stopservice  
 }

To stop service:

if in your activity:

Intent startServiceIntent = new Intent(this, EmailService.class);
this.stopService(startServiceIntent);
this.startService(startServiceIntent);

If inside service:

stopSelf();
TheDevMan
  • 5,914
  • 12
  • 74
  • 144
  • Hey thanks for giving an answer. I have got solution of it but i want to send an email when my checkbox button is checked. then how can i do that??? – Dharmesh Sep 19 '14 at 05:23
  • Hey thanks for reply.but i want to do that when my checkbox is checked then every 24 hours mail could be sent to user automatically. and if checkbox is unchecked then it will not be send.is it possible or not??? – Dharmesh Sep 19 '14 at 06:54
  • @Dharmesh: Yes, just use the first part insert the email service condition inside the checkBox.isChecked()==true. – TheDevMan Sep 19 '14 at 06:58
  • hey see i have edited my code now please tell me where i can call this stop service method?? i have already called that method in a else part of main activity but not work.. – Dharmesh Sep 19 '14 at 11:27
  • @Dharmesh: Where do you want to stopService inside intentService class if so - The IntentService is built to stop itself when the last Intent is handled by onHandleIntent(Intent) - i.e. you do not need to stop it, it stops it self when it's done. – TheDevMan Sep 19 '14 at 11:32