我想创建一个在通知中显示的计数器。即使屏幕被锁定,更新的通知也应一直保持更新(或者当屏幕显示带有通知的锁定屏幕时,应更新更新的通知。
我创建了服务来更新通知中的文本。解锁设备屏幕后,一切都很好(通知一直在更新)。当设备屏幕锁定时,服务仅在一段时间内更新通知。
服务:
public class MySimpleService extends Service {
private Notifi notifi;
private SimpleCounter counter;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
notifi = new Notifi(this);
startForeground(NOTIFICATION_ID, notifi.getNotification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int countTo = 100;
counter = new SimpleCounter(countTo, tic -> notifi.updateText(Integer.toString(tic)));
counter.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
stopForeground(true);
super.onDestroy();
}
}
计数器:
public class SimpleCounter {
public interface Listener {
void tic(int tic);
}
private int countTo;
private Listener listener;
public SimpleCounter(int countTo, Listener listener){
this.countTo = countTo;
this.listener = listener;
}
public void start(){
for (int i = 0; i < countTo; i++) {
wait1sec();
tic(i);
}
}
private void tic(int i) {
listener.tic(i);
}
private void wait1sec() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我如何运行服务:
Intent intent = new Intent(this, MySimpleService.class);
ContextCompat.startForegroundService(this, intent);