如何在应用程序关闭后保留警报管理器 运行?

How to keep Alarm Manager running even after the app closes?

我想要我的 MainActivity.java 文件中的 AlarmManager 每分钟都会触发一个 IntentService。

我写的代码是:

public void scheduleAlarm() {
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    long firstMillis = System.currentTimeMillis();
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 60000, pendingIntent);
}

这是我的 IntentService:

public class MyTestService extends IntentService {

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

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("tag_tag_tag", "Service running");

        String filename = "example.txt";
        String fileContents = "\ndone ";
        FileOutputStream fos = null;

    try {
            fos = openFileOutput(filename, MODE_APPEND);
            fos.write(fileContents.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
       }

    }
}

这里我只是附加到一个文件,只是为了检查服务是否在应用程序关闭后运行,但它没有。

这是我的接收器: public class MyAlarmReceiver 扩展 BroadcastReceiver {

    public static final int REQEST_CODE = 12345;
    public static final String ACTION = "com.always_in_beta.bekar";

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyTestService.class);
        i.putExtra("foo", "bar");
        context.startService(i);
    }
}

我希望即使在应用程序关闭后每分钟在后台触发此服务。

AlarmManager 的使用非常不可靠,尤其是从 Android M 开始。 phone 瞌睡模式会忽略警报事件。我使用 Firebase JobDispatcher https://github.com/firebase/firebase-jobdispatcher-android 非常适合这个目的。代码: Gradle:

implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

工作class:

import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;

public class MyTestService extends JobService {
@Override
public boolean onStartJob(JobParameters job) {
    // something like
 Log.d("tag_tag_tag", "Service running");

    String filename = "example.txt";
    String fileContents = "\ndone ";
    FileOutputStream fos = null;

try {
        fos = openFileOutput(filename, MODE_APPEND);
        fos.write(fileContents.getBytes());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
   }

    return false; // Answers the question: "Is there still work going on?"
}

@Override
public boolean onStopJob(JobParameters job) {
    return false; // Answers the question: "Should this job be retried?"
}

}

清单:

<service
android:exported="false"
android:name=".MyTestService">
<intent-filter>
    <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>

在您的 activity 中,创建调度程序:

// Create a new dispatcher using the Google Play driver.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));

然后安排作业:

Job myJob = dispatcher.newJobBuilder()
.setService(MyTestService.class) // the JobService that will be called
.setTag("my-unique-tag")        // uniquely identifies the job
.setRecurring(true)
.setTrigger(Trigger.executionWindow(1*60-10,1*60+10))//1 minute +/- 10 seconds
.build();

dispatcher.mustSchedule(myJob);

这应该有用,至少对我有用。