对广播接收器使用 IntentService 而不是 AsyncTask?

Using IntentService instead of AsyncTask for Broadcast Receiver?

我正在尝试使用 BroadcastReceiver 发送电子邮件,代码在使用 onClick 时使用 AsyncTask 正常工作,但在调用 AlarmReceiver 时不起作用。

这个方法用IntentService会不会更好?如果是这样,最好的写法是什么?

谁能帮忙解决这个问题?我对 java 还是个新手,想帮助提高我的知识。 :)

如有任何帮助,我们将不胜感激!谢谢!

AlarmReceiver.java

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.content.BroadcastReceiver;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import static android.graphics.Color.GREEN;

public class AlarmReceiver extends BroadcastReceiver {

Context cxt;
Activity context;

@Override
public void onReceive(Context arg0, Intent arg1) {

    cxt = arg0;

    addNotification();
    new SendMail().execute();
}


private class SendMail extends AsyncTask<String, Integer, Void> {

    protected Void doInBackground(String... params) {
        Mail m = new Mail("youremail@gmail.com", "password");

        String[] toArr = {"toemail@outlook.com"};
        m.setTo(toArr);
        m.setFrom("fromemail@gmail.com");
        m.setSubject("Achieve Alert!");
        m.setBody("This is a reminder about your upcoming assignment or examination!");

        try {
            if(m.send()) {
                Toast.makeText(context.getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context.getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
            }
        } catch(Exception e) {
            Log.e("MailApp", "Could not send email", e);
        }
        return null;
    }
}
}

首先从警报管理器启动 Intent 服务:

 private void setAlarm(Calendar targetCal){

   /* HERE */     Intent intent = new Intent(getBaseContext(), AlarmService.class);
        final int _id = (int) System.currentTimeMillis();

      /* HERE */  PendingIntent pendingIntent = PendingIntent.getService(this,_id,intent,PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    ......
    .....

现在意向服务class:

 public class AlarmService extends IntentService {

PowerManager powerManager;
    PowerManager.WakeLock wakeLock;

public AlarmService() {
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FCFCFCFC");

        wakeLock.acquire();

       addNotification();
       sendMAIL();

    }


    public void addNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.icon_transperent)
                    .setLights(GREEN, 700, 700)
                    .setContentTitle("Achieve - Alert!")
                    .setContentText("This is a reminder for your deadline!");

    Intent notificationIntent = new Intent(getApplicationContext(), MainMenu.class);
    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,     notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    builder.setVibrate(new long[] { 0, 1000, 1000, 1000, 1000 });
    manager.notify(0, builder.build());
}

    public void sendMAIL(){

    Mail m = new Mail("youremail@gmail.com", "password");

        String[] toArr = {"toemail@outlook.com"};
        m.setTo(toArr);
        m.setFrom("fromemail@gmail.com");
        m.setSubject("Achieve Alert!");
        m.setBody("This is a reminder about your upcoming assignment or examination!");

        try {
            if(m.send()) {
                Toast.makeText(getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
            }
        } catch(Exception e) {
            Log.e("MailApp", "Could not send email", e);
        }


        wakeLock.release();

    }


     @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

现在,清单添加:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<service android:name=".AlarmService" android:exported="true" android:enabled="true"/>