java如何使我的秒表应用程序在完全关闭后仍能运行?
如何使我的秒表应用程序运行,即使在应用程序已完全关闭
主要活动。爪哇
package com.study.meter;
import 安卓x.appcompat.app.AppCompatActivity;
import 安卓.view.View;
import 安卓.os.Bundle;
import 安卓.widget.TextView;
import 安卓.widget.Button;
import 安卓.os.Handler;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
public TextView StopWatch;
public boolean isStopWatchRunning = false;
public int stopWatchSecs = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// hide actionbar
this.getSupportActionBar().hide();
// set the value of StopWatch
StopWatch = findViewById(R.id.StopWatch);
}
public void StartorStop(View v)
{
Button sv = (Button)v;
if(isStopWatchRunning)
{
isStopWatchRunning=false;
sv.setText("Start");
}else
{
isStopWatchRunning=true;
sv.setText("Stop");
}
// Creates a new Handler
final Handler handler
= new Handler();
// Call the post() method,
// passing in a new Runnable.
// The post() method processes
// code without a delay,
// so the code in the Runnable
// will run almost immediately.
handler.post(new Runnable() {
@Override
public void run()
{
int hours = stopWatchSecs / 3600;
int minutes = (stopWatchSecs % 3600) / 60;
int secs = stopWatchSecs % 60;
// Format the stopWatchSecs into hours, minutes,
// and stopWatchSecs.
String time
= String
.format(Locale.getDefault(),
"%d:%02d:%02d", hours,
minutes, secs);
// Set the text view text.
// If running is true, increment the
// stopWatchSecs variable.
if (isStopWatchRunning) {
StopWatch.setText(time);
stopWatchSecs++;
handler.postDelayed(this, 1000);
}
// Post the code again
// with a delay of 1 second.
}
});
}
}
但是,当应用程序关闭时,会重新启动秒表, 如何使这个秒表不停止后,应用程序已关闭或销毁,或设备已重新启动或关闭
我想说的是我希望它在后台继续运行
编辑
也许像这个数学方程式
应用程序关闭时间=14:20:-00 应用程序关闭时秒表读数=23秒 (将此数据保存到存储器中)
应用程序重新打开的时间=14:25:00 秒表的最后读数=23秒
因此,秒表的值为=(14:25:00-14:20:00)+23秒=5分钟+23秒=323秒
# 1 楼答案
理论上,你可以将计时器的开始时间存储在本地存储器中,然后根据该值在应用程序再次启动时恢复
# 2 楼答案
你必须制作一个在后台运行的服务。Whatsapp在后台有一个服务,所以每当一个新的通知出现并完全关闭时,通知也会出现
请参见以下链接以供参考:
Creating Background Service in Android
Android Developer Doc
编辑:将计时器代码放入扩展服务的类中
# 3 楼答案
尝试使用JobScheduler来实现这一点