Using IntentService instead of AsyncTask for Broadcast Receiver?

て烟熏妆下的殇ゞ 提交于 2019-12-13 07:08:58

问题


I am in the process of trying to get an email sent using BroadcastReceiver, the code is working correct using AsyncTask when using onClick but does not work when AlarmReceiver is being called.

Would it be better to use IntentService for this method? If so, what is the best way to write this?

Can anyone help with this problem? I am still new to java and want to help improve my knowledge. :)

Any help would be appreciated! Thank you!

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;
    }
}
}

回答1:


First start Intent service from Alarm manager :

 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);
    ......
    .....

Now Intent 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();
    }
}

Now, Manifest add:

<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"/>


来源:https://stackoverflow.com/questions/42859196/using-intentservice-instead-of-asynctask-for-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!