如何使用BroadcastReceiver在Android中发送电子邮件?

时间:2014-08-19 06:11:48

标签: java android email alarmmanager

我正在尝试创建警报管理器,以便在我的应用程序中发送特定日期的电子邮件。我在特定的日期和时间使用BroadcastReceiver发送电子邮件。我希望当用户点击我的应用程序“发送”按钮时,它应该发送特定日期和时间的电子邮件。可以请一些人帮我。这很紧急。谢谢欣赏

这是我的活动代码

public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form_details);

         etServiceName = (EditText)findViewById(R.id.editText_ServiceName);
         etSupplierName = (EditText)findViewById(R.id.editText_SupplierName);
         etEmailId = (EditText)findViewById(R.id.Edittext_EmailId);
         etReplacementDate = (EditText)findViewById(R.id.EditText_ReplacementDate);
         etInterval_Days = (EditText)findViewById(R.id.EditText_IntervalDays);
         etNextReplanishmentDate = (EditText)findViewById(R.id.Next_Replanishment_Date);

        // Get current date by calender
         final Calendar c = Calendar.getInstance();
         year  = c.get(Calendar.YEAR);
         month = c.get(Calendar.MONTH);
         day   = c.get(Calendar.DAY_OF_MONTH);


         etReplacementDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showDialog(DATE_OF_REPLACEMENT);
            }
        });



            etInterval_Days.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable editable) 
                {
                    // TODO Auto-generated method stub
                     String fixedDate = etReplacementDate.getText().toString().trim();
                     SimpleDateFormat dateFormat1 = new SimpleDateFormat( "dd-MM-yyyy" );
                       Calendar cal = Calendar.getInstance();
                       try
                       {
                                cal.setTime( dateFormat1.parse( fixedDate ) );
                       } 
                       catch (ParseException e) 
                       {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                       }

                       String strNumDays = etInterval_Days.getText().toString().trim();
                       if(strNumDays.trim().length()>0)
                       {
                           try
                              { 
                                  intConvertDays =Integer.valueOf(strNumDays);
                              }
                              catch(NumberFormatException ne)
                              {
                                 System.out.println("could not parse :: " +ne);
                              }

                       }


                       cal.add( Calendar.DATE, intConvertDays );
                       Date dated = cal.getTime();
                       String beforDate_String = new SimpleDateFormat("dd-MM-yyyy").format(dated);
                       System.out.println("beforDate_String: " + beforDate_String);
                       etNextReplanishmentDate.setText(beforDate_String);

                       cal.add( Calendar.DATE, -2 );
                       Date minusDate = cal.getTime();
                       strMinusDate = new SimpleDateFormat("dd-MM-yyyy").format(minusDate);
                       System.out.println("String strMinusDate : " + strMinusDate);


                       if(strMinusDate.trim().length()>0)
                       {
                           try
                              { 
                                IntMinusDate =Integer.valueOf(strMinusDate);
                                System.out.println(" IntMinusDate = " + IntMinusDate);
                              }
                              catch(NumberFormatException ne)
                              {
                                 System.out.println("could not parse :: " +ne);
                              }

                       }


                }
            });


         Intent intentAlarm = new Intent(Xyz.this, EmailSendTask.class);

         // create the object
         final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

         final PendingIntent pIntent = PendingIntent.getBroadcast(this,(int) IntMinusDate,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);




         btnSubmit = (Button) findViewById(R.id.buttonSubmit);
         btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                 strEmail= etEmailId.getText().toString().trim();

                         strServiceName =  etServiceName.getText().toString().trim();
                         strSuppliername= etSupplierName.getText().toString().trim();
                         strReplacementDate= etReplacementDate.getText().toString().trim();
                         strIntervalDays= etInterval_Days.getText().toString().trim();
                         strNextReplacementDate = etNextReplanishmentDate.getText().toString().trim();
                         System.out.println("Data :- " + strServiceName +","+ strSuppliername +","+ strEmail +","+ strReplacementDate +","+ strIntervalDays + "," + strNextReplacementDate);

                         SharedPreferences sharedPref =getSharedPreferences("MyPref_Email", 0);
                         SharedPreferences.Editor editor1 = sharedPref.edit();

                         editor1.putString("ServiceName", strServiceName);
                         editor1.putString("Suppliername", strSuppliername);
                         editor1.putString("Email", strEmail);
                         editor1.putString("ReplacementDate", strReplacementDate);
                         editor1.putString("IntervalDays", strIntervalDays);
                         editor1.putString("NextReplacementDate", strNextReplacementDate);

                         editor1.commit();
                         Log.e("Commit is Complit", "Save");

                         //sendEmail();
                         System.out.println("Email Has To Be Sent Successfully");

                         databaseHelper.insertServicenDetails(strServiceName, strSuppliername, strEmail, strReplacementDate, strIntervalDays, strNextReplacementDate);
                         System.out.println("Data Has Been Save Successfully");


                        //set the alarm for particular time
                         alarmManager.set(AlarmManager.RTC_WAKEUP,IntMinusDate, pIntent);
                         System.out.println("set the alarm for particular time  : ");

             }
        });
}

这是我的BroadcastReceiver代码

public class EmailSendTask extends BroadcastReceiver
{
    String strServiceName;
    String strSuppliername;
    String strEmail;
    String strReplacementDate;
    String strIntervalDays;
    String strNextReplacementDate;

    @Override
    public void onReceive(Context context, Intent arg1)
    {
        // TODO Auto-generated method stub
        SharedPreferences prefs = context.getSharedPreferences("MyPref_CellNumber", 
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = prefs.edit();

         strServiceName=prefs.getString("ServiceName" , "a\n");
         strSuppliername=prefs.getString("Suppliername" , "a\n");
         strEmail=prefs.getString("Email" , "a\n");
         strReplacementDate=prefs.getString("ReplacementDate" , "a\n");
         strIntervalDays=prefs.getString("IntervalDays" , "a\n");
         strNextReplacementDate=prefs.getString("NextReplacementDate" , "a\n");

         Log.e("ON CREATE" , "=" + strServiceName);
         Log.e("ON CREATE" , "=" + strSuppliername);
         Log.e("ON CREATE" , "=" + strEmail);
         Log.e("ON CREATE" , "=" + strReplacementDate);
         Log.e("ON CREATE" , "=" + strIntervalDays);
         Log.e("ON CREATE" , "=" + strNextReplacementDate);

                            String subject = strServiceName;

                            String body = strServiceName+","
                                          +strSuppliername+","
                                          +strReplacementDate+","
                                          +strIntervalDays+","
                                          +strNextReplacementDate;

                           Log.e("body " , " = " + body);

                          Intent i = new Intent(Intent.ACTION_SEND);
                          i.setType("message/rfc822");
                          i.putExtra(Intent.EXTRA_EMAIL  , new String[]{strEmail});
                          i.putExtra(Intent.EXTRA_SUBJECT, subject);
                          i.putExtra(Intent.EXTRA_TEXT   , body);
                          i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                          try 
                          {
                              context.startActivity(Intent.createChooser(i, "Send mail...in Service Background"));    

                          } 
                          catch (android.content.ActivityNotFoundException ex) 
                          {
                              Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
                          }
    }


}

这是log cat Error

08-19 11:39:13.797: E/AndroidRuntime(485): FATAL EXCEPTION: main
08-19 11:39:13.797: E/AndroidRuntime(485): java.lang.RuntimeException: Unable to start receiver com.demo.EmailSendTask: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:1805)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.app.ActivityThread.access$2400(ActivityThread.java:117)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.os.Looper.loop(Looper.java:123)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-19 11:39:13.797: E/AndroidRuntime(485):  at java.lang.reflect.Method.invokeNative(Native Method)
08-19 11:39:13.797: E/AndroidRuntime(485):  at java.lang.reflect.Method.invoke(Method.java:507)
08-19 11:39:13.797: E/AndroidRuntime(485):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-19 11:39:13.797: E/AndroidRuntime(485):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-19 11:39:13.797: E/AndroidRuntime(485):  at dalvik.system.NativeStart.main(Native Method)
08-19 11:39:13.797: E/AndroidRuntime(485): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.app.ContextImpl.startActivity(ContextImpl.java:621)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.content.ContextWrapper.startActivity(ContextWrapper.java:258)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.content.ContextWrapper.startActivity(ContextWrapper.java:258)
08-19 11:39:13.797: E/AndroidRuntime(485):  at com.demo.EmailSendTask.onReceive(EmailSendTask.java:63)
08-19 11:39:13.797: E/AndroidRuntime(485):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:1794)
08-19 11:39:13.797: E/AndroidRuntime(485):  ... 10 more

2 个答案:

答案 0 :(得分:0)

INVINCIBLE android告诉所有事情

只是你必须让你的眼睛睁开......

由以下原因引起:android.util.AndroidRuntimeException:从Activity上下文外部调用startActivity()需要FLAG_ACTIVITY_NEW_TASK标志。这真的是你想要的吗?

logcat会告诉你第一行的问题是什么

Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag

添加该标志

Intent i = new Intent(context, maven.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(i);
parentActivity.finish();

您可以获取所有可用Intent Flags here in the docs

的列表

答案 1 :(得分:0)

这是因为Intent.FLAG_ACTIVITY_NEW_TASK丢失了。 Intent.createChooser(i,“在服务背景中发送邮件...”)将生成一个新意图,因此我们应该再次设置它。见http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.L_preview/android/content/Intent.java#Intent.createChooser%28android.content.Intent%2Cjava.lang.CharSequence%29

尝试以下代码

try 
{
    Intent intent = Intent.createChooser(i, "Send mail...in Service Background");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);    

} catch (android.content.ActivityNotFoundException ex){
    Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}