我是Android编程的新手,我有一个问题。
当我触摸屏幕时,我有一个倒数从60倒数到零。 我现在想要即使在调用onDestroy时,这个倒计时将在Activity生命周期中存活下来。所以我需要一个服务。
Wenn倒计时结束后会发送通知。但是,如果用户想要在服务倒计时结束之前再次打开应用程序,则不应发出任何通知,并且必须停止服务。
实施这些功能的最佳做法是什么?这是怎么回事?
非常感谢您的回答!
我的方法是我有一个带倒计时方法和服务的课程
// Countdownclass TimerClass.java
public class TimerClass {
private static final String TAG = "MyLog";
private static final long TIMERINTERVAL = 1000;
//Eigenschaften --------------------------------------------------------------------
private boolean isActiv = false;
private Paint paint;
private long timerTime;
private double actualTime;
private int x;
private int y;
private CountDownTimer countDownTimer;
private String timeString;
//Konstruktor --------------------------------------------------------------------
public TimerClass(int x, int y) {
this.x = x;
this.y = y;
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.YELLOW);
paint.setAntiAlias(true);
paint.setTextAlign(Align.RIGHT);
paint.setTextSize(70);
}
public TimerClass() {
}
//Methoden --------------------------------------------------------------------
public void draw(Canvas canvas) {
if(isActiv) {
canvas.drawText(timeString, x, y, paint);
}
}
public void createTimer(long timerTime) {
this.timerTime = timerTime;
countDownTimer = new CountDownTimer(timerTime, TIMERINTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
actualTime = (double) millisUntilFinished / TIMERINTERVAL;
NumberFormat nf = new DecimalFormat("##.#");
nf.format(actualTime);
if(actualTime < 10) {
new DecimalFormat();
timeString = "0:0" + nf.format(actualTime - 1);
} else {
timeString = "0:" + nf.format(actualTime - 1);
}
}
@Override
public void onFinish() {
isActiv = false;
}
};
}
public void timerStart() {
countDownTimer.start();
isActiv = true;
}
public void timerStop() {
if(isActiv) {
countDownTimer.cancel();
}
isActiv = false;
}
public boolean isActiv() {
return isActiv;
}
public void setActiv(boolean isActiv) {
this.isActiv = isActiv;
}
public double getActualTime() {
return actualTime;
}
public void setActualTime(double actualTime) {
this.actualTime = actualTime;
}
我的服务:
public class TimerService extends Service {
//class with the countdowntimer
private TimerClass timerClass;
private long startTime;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
timerClass = new TimerClass();
startTime = (long) timerClass.getActualTime();
timerClass.createTimer(startTime);
}
@Override
public void onDestroy() {
timerClass.timerStop();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
timerClass.timerStart();
if(timerClass.getActualTime() <= 0) {
// send the notification
}
return super.onStartCommand(intent, flags, startId);
}
我想在mainActivies onPause方法中启动服务,并在调用onResume时停止它。但是我已经尝试了很多次但都失败了......所以我的活动中没有代码供我服务。
(抱歉我的英语不好:()