使用IntentService而不是AsyncTask进行广播接收? [英] Using IntentService instead of AsyncTask for Broadcast Receiver?

查看:85
本文介绍了使用IntentService而不是AsyncTask进行广播接收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取使用BroadcastReceiver发送的电子邮件,使用onClick时,使用AsyncTask可使代码正常工作,但调用AlarmReceiver时,则无法正常工作.

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.

为此方法使用IntentService会更好吗?如果是这样,最好的写法是什么?

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

有人可以帮助解决这个问题吗?我对Java还是很陌生,想帮助我提高知识. :)

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

推荐答案

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

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

现在的Intent 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();
    }
}

现在,清单添加:

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

这篇关于使用IntentService而不是AsyncTask进行广播接收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆