Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对广播接收器使用IntentService而不是AsyncTask?_Java_Android_Xml_Android Asynctask_Intentservice - Fatal编程技术网

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

Java 对广播接收器使用IntentService而不是AsyncTask?,java,android,xml,android-asynctask,intentservice,Java,Android,Xml,Android Asynctask,Intentservice,我正在尝试使用BroadcastReceiver发送电子邮件,使用onClick时使用AsyncTask代码工作正常,但在调用AlarmReceiver时代码不工作 对于此方法,使用IntentService是否更好?如果是这样,写这篇文章的最佳方式是什么 有人能帮忙解决这个问题吗?我对java还是新手,希望帮助提高我的知识。:) 任何帮助都将不胜感激!谢谢大家! AlarmReceiver.java import android.app.Activity; import android.app

我正在尝试使用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;
    }
}
}
导入android.app.Activity;
导入android.app.NotificationManager;
导入android.app.pendingent;
导入android.content.Context;
导入android.content.Intent;
导入android.support.v4.app.NotificationCompat;
导入android.content.BroadcastReceiver;
导入android.os.AsyncTask;
导入android.util.Log;
导入android.widget.Toast;
导入静态android.graphics.Color.GREEN;
公共类AlarmReceiver扩展了BroadcastReceiver{
上下文cxt;
活动语境;
@凌驾
公共void onReceive(上下文arg0,意图arg1){
cxt=arg0;
添加通知();
新建SendMail().execute();
}
私有类SendMail扩展了异步任务{
受保护的Void doInBackground(字符串…参数){
邮件m=新邮件(“youremail@gmail.com“,”密码“);
字符串[]toArr={”toemail@outlook.com"};
m、 设置为(toArr);
m、 setFrom(“fromemail@gmail.com");
m、 setSubject(“实现警报!”);
m、 setBody(“这是对您即将进行的作业或考试的提醒!”);
试一试{
if(m.send()){
Toast.makeText(context.getApplicationContext(),“电子邮件已成功发送。”,Toast.LENGTH_LONG.show();
}否则{
Toast.makeText(context.getApplicationContext(),“电子邮件未发送”,Toast.LENGTH_LONG.show();
}
}捕获(例外e){
Log.e(“MailApp”,“无法发送电子邮件”,e);
}
返回null;
}
}
}

报警管理器的首次启动意图服务:

 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);
    ......
    .....
现在,意向服务类:

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

报警管理器的首次启动意图服务:

 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);
    ......
    .....
现在,意向服务类:

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



是,从Wakefulbrodcast启动intent服务,不要在服务中使用asynctask谢谢您的回复。我该怎么做?我对java还是一个新手,现在还在学习。重写WakeFullBrodcastReceiver和onmessage Received start IntentService类的内部。谢谢,你能给出一个这样的例子,以便我能清楚地理解,而不是使用AsyncTask来代替SendMail()方法;是的,从Wakefulbrodcast启动intent服务,不要在服务中使用asynctask谢谢回复。我该怎么做?我对java还是一个新手,现在还在学习。重写WakeFullBrodcastReceiver和onmessage Received start IntentService类的内部。谢谢,你能给出一个这样的例子,以便我能清楚地理解,而不是使用AsyncTask来代替SendMail()方法;感谢您的帮助,我已经尝试了您发布的内容,但是当到达时间时,不会触发任何内容,也不会通知设备或电子邮件。也没有错误。我已确保将代码也包含在清单中。是否AlarmService不再扩展BroadcastReceiver?我不知道为什么什么都没有被触发。不需要使用brodcast接收器。你重启设备了吗?发布你的新代码啊,好的,谢谢。现在,我已经用我在“可能的工作代码”下添加的内容更新了我的原始帖子,我在logcat中遇到的错误是:03-18 15:51:00.660 1533-1577/system_process W/ActivityManager:cannot start service Intent{flg=0x4 cmp=com.example.pc.each/.AlarmService(has extras)}U=0:未找到请尝试将整个服务名称放在menifest中,而不是。AlarmService感谢您的帮助,我已尝试了您发布的内容,但当到达时间时,不会触发任何内容,也不会通知设备或电子邮件。也没有错误。我已确保将代码也包含在清单中。是否AlarmService不再扩展BroadcastReceiver?我不知道为什么什么都没有被触发。不需要使用brodcast接收器。你重启设备了吗?发布你的新代码啊,好的,谢谢。现在,我已经用我在“可能的工作代码”下添加的内容更新了我的原始帖子,我在logcat中遇到的错误是:03-18 15:51:00.660 1533-1577/system_process W/ActivityManager:cannot start service Intent{flg=0x4 cmp=com.example.pc.each/.AlarmService(has extras)}U=0:未找到请尝试将整个服务名称放在menifest中,而不是.AlarmService中