Search code examples
androidemailbroadcastreceiver

Send an Email when the network is available


I am developing an android application for scheduling an email to be sent at specified time.
Now I succeeded by setting a broadcast receiver and using a pending intent.
Now the problem is: suppose that at the scheduled network or internet connection is not available, how can I achieve that action?
I can register a broadcast receiver for the internet connection but i don't know how to use it then.
Help me out.

whenever the user sets time I am calling this setAlarm method()

   private void setAlarm(Calendar targetCal) {

         email = editTextEmail.getText().toString();
         subject = editTextSubject.getText().toString();
         message = editTextMessage.getText().toString();
        //
        Toast.makeText(AlarmActivity.this, "Mail Scheduled at " + targetCal.getTime(),
                Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getBaseContext(), AlarmReciever.class);
        int uniqueValue = (int) System.currentTimeMillis();
        intent.putExtra("email", email);
        intent.putExtra("sub", subject);
        intent.putExtra("msg", message);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getApplicationContext(), uniqueValue, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
                pendingIntent);
        AlarmActivity.this.finish();

    }

At onReceive method i will call send email method()

  public static void sendMail(Context c,String em, String sub,String msg){
    try {

        sender.sendMail(sub, msg, un, em);
        Toast.makeText(c, "Mail Being Sent",Toast.LENGTH_LONG).show();
       no.flags=Notification.FLAG_AUTO_CANCEL; 
        nf.notify(Notify,no);

  } catch (Throwable t) {
        Toast.makeText(c,
                      "There are problem with sending mail. ",
                      Toast.LENGTH_LONG).show();
        mgr.notify(fail, note);

  }
}

Solution

  • android.net.conn.CONNECTIVITY_CHANGE

    android.net.wifi.WIFI_STATE_CHANGED

    Whenever the network status changes i.e if it connects or disconnects, you will get these two broadcasts. You can receive these broadcasts and can send the email.

    For more info you can refer this tutorial

    http://viralpatel.net/blogs/android-internet-connection-status-network-change/