Android/XixunPlayer/app/src/main/java/com/xixun/xixunplayer/SrcCountdown.java

99 lines
3.0 KiB
Java
Raw Normal View History

2024-01-24 20:17:59 +08:00
package com.xixun.xixunplayer;
import android.content.Context;
import android.graphics.Color;
import android.view.Choreographer;
import android.view.View;
import android.webkit.WebView;
import androidx.annotation.NonNull;
2024-01-25 20:43:39 +08:00
import java.text.SimpleDateFormat;
2024-01-24 20:17:59 +08:00
import gnph.util.JSMap;
import gnph.util.NumFmts;
public class SrcCountdown extends WebView implements Choreographer.FrameCallback {
long targetTime;
2024-01-25 20:43:39 +08:00
String html, lineHeight, prefix;
2024-01-24 20:17:59 +08:00
boolean hasDay, hasHour, hasMin, hasSec;
public SrcCountdown(Context context, JSMap json) {
super(context);
2024-01-25 20:43:39 +08:00
setBackgroundColor(Color.TRANSPARENT);
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
setInitialScale(100);
html = json.stnn("html");
lineHeight = json.str("lineHeight");
prefix = "<body style=\"color:#fff;margin:0;padding:0;";
if(lineHeight!=null) prefix += "line-height:"+lineHeight+";";
prefix += "\">";
hasDay = html.contains("%d");
hasHour = html.contains("%h");
hasMin = html.contains("%m");
hasSec = html.contains("%s");
var time = json.stnn("time");
2024-01-24 20:17:59 +08:00
try {
2024-01-25 20:43:39 +08:00
try {
targetTime = new SimpleDateFormat("y-M-d H:m:s").parse(time).getTime() / 1000;
} catch (Exception e) {
targetTime = new SimpleDateFormat("y-M-d H:m").parse(time).getTime() / 1000;
}
2024-01-24 20:17:59 +08:00
} catch (Exception e) {
Util.printStackTrace(e);
Util.makeText(context, Util.toStr(e)).show();
}
}
void cal() {
var cur = System.currentTimeMillis() / 1000;
var secs = targetTime - cur;
if(secs < 0) secs = 0;
var htm = html;
if(hasDay) {
2024-01-25 20:43:39 +08:00
htm = htm.replace("%d", Long.toString(secs/86400));
2024-01-24 20:17:59 +08:00
secs %= 86400;
}
if(hasHour) {
2024-01-25 20:43:39 +08:00
htm = htm.replace("%h", NumFmts.zz().format(secs/3600));
2024-01-24 20:17:59 +08:00
secs %= 3600;
}
if(hasMin) {
2024-01-25 20:43:39 +08:00
htm = htm.replace("%m", NumFmts.zz().format(secs/60));
2024-01-24 20:17:59 +08:00
secs %= 60;
}
2024-01-25 20:43:39 +08:00
if(hasSec) htm = htm.replace("%s", NumFmts.zz().format(secs));
loadDataWithBaseURL(null, prefix+htm+"</body>", "text/html", "UTF-8", null);
2024-01-24 20:17:59 +08:00
}
@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if(visibility==View.VISIBLE) {
if(lastSec==0) {
cal();
choreographer.postFrameCallback(this);
lastSec = 1;
}
}
}
Choreographer choreographer = Choreographer.getInstance();
long lastSec;
@Override
public void doFrame(long frameTimeNanos) {
if(! isShown()) {
lastSec = 0;
return;
}
var sec = System.currentTimeMillis() / 1000;
if(sec != lastSec) {
lastSec = sec;
cal();
}
choreographer.postFrameCallback(this);
}
}