有状态的AlarmManager吗?

时间:2019-07-17 02:43:45

标签: android alarmmanager android-jetpack

我正在开发一个Android通知应用程序,该应用程序会更新UI并每隔X秒通知一次

我需要启动服务,比较并存储一些变量,通知和更新UI,每隔x秒重复一次。问题在于每次都会调用BroadcastReceiver的onReceive()和JobIntentService的onCreate()。

我需要一个可以保持状态的AlarmManager / JobIntentService。

  

MainActivity(更新UI)-> AlarmManager-> BroadcastReceiver->   JobIntentService(获取数据并发送通知)

从MainActivity调用AlarmManager:

public void startAlarm() {
    Intent myAlarm = new Intent(getApplicationContext(), AlarmReceiver.class);
    myAlarm.putExtra("messenger", new Messenger(handler));
    PendingIntent recurringAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, myAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), SimpleJobIntentService.interval * 1000, recurringAlarm);
}

广播接收器:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent myService = new Intent(context, SimpleJobIntentService.class);
    myService.putExtra("messenger", (Messenger) intent.getExtras().get("messenger"));
    SimpleJobIntentService.enqueueWork(context, myService);
}
}

JobIntentService:

public class SimpleJobIntentService extends JobIntentService {

static final int JOB_ID = 1000;

private Messenger messenger;

static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, SimpleJobIntentService.class, JOB_ID, work);
}

@Override
public void onCreate() {
    super.onCreate();
    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        messenger = (Messenger) bundle.get("messenger");
    }
    // createNotificationChannel
    // init     
}


@Override
protected void onHandleWork(Intent intent) {
     // get data from DB, compare variables and store them in another variable
     // notify
     // send message to MainActivity's Handler
}
}

0 个答案:

没有答案