gpt4 book ai didi

android - 在android中定期运行asynctask

转载 作者:太空狗 更新时间:2023-10-29 16:18:58 24 4
gpt4 key购买 nike

在这里,我必须以每 5 秒的间隔周期性地运行一个异步任务。下面是我的代码,

//每隔5秒调用asynctask

    final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask()
{
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try
{
new PerformBackgroundTask().execute();

}
catch (Exception e)
{

}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 5s*



}

//每隔5秒调用asynctask

public class PerformBackgroundTask extends AsyncTask<Void, Void, Void>
{


@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Call at interval of 5 seconds" + "" + count , 500).show();

}
});
count++;
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

}
}

当我运行我的应用程序时,它是第一次完全运行,这意味着每 5 秒就会出现一次 toast 消息。现在,当我关闭应用程序并再次重新启动时,会出现两条 toast 消息(意味着我可以这样说,创建了类的第二个实例),并且每次我重新启动应用程序时都会创建新的 toast 消息。每次我重新启动我的应用程序时,我只想要一条 toast 消息(第一个)。我该怎么做?

最佳答案

您应该使用带有警报管理器的服务而不是计时器任务。

检查 this one

this one

关于android - 在android中定期运行asynctask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20372704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com