我正在尝试设置一个警报管理器,使其每 15 分钟运行一次,检查是否有任何内容已添加到数据库中,然后显示通知。然而,虽然我只是对此进行测试,但我试图在 60 秒后显示通知。
当应用程序打开或最小化时,下面的代码可以完美运行,但在应用程序关闭时永远不会被调用。
主要活动(onCreate())
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if (!alarmRunning) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent);
}
Run Code Online (Sandbox Code Playgroud)
报警接收器
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
Run Code Online (Sandbox Code Playgroud)
}
后台服务
public class BackgroundService extends Service {
private final String TAG = getClass().getName();
private …Run Code Online (Sandbox Code Playgroud) android alarmmanager android-intent android-service android-notifications
我目前正在开发一个电子邮件应用程序,它依赖于背景service以便能够自动获取新电子邮件。当应用程序打开(或在应用程序的运行列表中)时,此功能完美运行,但一旦我关闭应用程序/将其从最近的应用程序列表中删除,它service也会停止。可以通过进入设备上的“开发人员设置”并查看没有为我的应用程序运行的进程或服务来确认这一点。
我在 StackOverflow 上读过无数的帖子,但似乎没有一个能成功。有时onTaskRemoved() 被调用并且服务被重新启动,但其他时候它根本没有被调用或者被调用,日志显示操作系统已安排重新启动,但service随后由操作系统service获取forced closed,而我总是需要运行此服务以检索新电子邮件。
我当前的代码如下所示:
我的服务:
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i(TAG, "onStartCommand()");
...
Log.d(TAG, "SERVICE IS RUNNING");
if (host != null) {
Log.d(TAG, "STARTING PUSH SERVICE");
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Log.d(TAG, "BR: " + ((BugReporting) getApplication())); …Run Code Online (Sandbox Code Playgroud) java service android background-service long-running-processes