AlarmManager - 我做得对吗?

AlarmManager - Am I doing it right?

我在 MainActivity class.

中设置了 AlarmManager

一个名为 AlarmReceiver 的 class 会在每个设定的时间间隔内启动。

我必须在 class 启动时执行操作。该代码在另一个 class Parsing.java

现在 AlarmReceiver.java,我正在这样做 :

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Parsing obj = new Parsing(context);

        obj.execute();

    }
}

我不能直接在 AlarmReceiver.java 中编写代码,因为 AlarmReceiver.java 已经在扩展 BroadcastReceiver 而我的代码 Parsing.java 正在扩展另一个 class .

因此,我正在为 Parsing class 创建一个对象并调用该方法。

我的做法正确吗?

如果需要,我会提供更多信息。 请让我知道我的方法是否正确? 提前致谢!

编辑:

Parsing.java

public class Parsing extends AsyncTask<Void, Void, Void> {

//some code

}

我不知道你是怎么写的Parsing.java,看起来不错,但记住这个

This method is always called within the main thread of its process, unless you explicitly asked for it to be scheduled on a different thread using registerReceiver. When it runs on the main thread you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed). You cannot launch a popup dialog in your implementation of onReceive()

对我来说,我认为处理这个问题的更好方法是在 onReceive 方法中调用另一个服务,就像这样

@Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, ParsingService.class);
        context.startService(i);
    }

BroadcastReceiver 开始 AsyncTask 是错误的,原因有二:

1. 运行 onReceive() 的线程在方法 returns 之后终止,有效地结束了任何 long-运行 任务可能是从那里开始的。引用官方docs:

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active ..... anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

2. onReceive()提供的Context实例与 ActivityServiceContext,即 Activity.thisService.this。您需要适当的 Context 来执行许多操作 我们通常从 ActivityService。因此,例如,在
中启动 Service 的正确方法 onReceive() 是:

@Override
public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(context.getApplicationContext(), ParsingService.class);
    context.getApplicationContext().startService(i);
}

而不是

@Override
public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(context, ParsingService.class);
    context.startService(i);
}