gpt4 book ai didi

android - 使特定代码在后台运行

转载 作者:太空宇宙 更新时间:2023-11-03 11:52:01 25 4
gpt4 key购买 nike

我想让这段代码在后台运行。正如大多数人指出的那样,我不知道如何创建服务或 Asynstask,因为它只需要是这段代码,而不是其他所有内容。

void StartTimer()
{
int minsTicks=CountM*60*1000;
int hoursTicks=CountT*60*60*1000;
int totalTicks=hoursTicks+minsTicks;
mTextField = (TextView) findViewById(R.id.TimerTextView);

CountDownTimer aCounter = new CountDownTimer(totalTicks, 1000)
{
public void onTick(long millisUntilFinished)
{
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish()
{
try
{
mTextField.setText("Kaffe Maskinen er igang");
mmOutputStream.write('2');
Thread.sleep(900000);
mmOutputStream.write('0');
mTextField.setText("Kaffe Maskinen er slukket");
}
catch (IOException e) {} catch (InterruptedException e) {}
}
};
aCounter.start();
}

最佳答案

这是 AsyncTask 的代码 fragment

private class AsyncTaskEx extends AsyncTask<Void, Void, Void> {

/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
@Override
protected Void doInBackground(Void... arg0) {
StartTimer();//call your method here it will run in background
return null;
}

/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
@Override
protected void onPostExecute(Void result) {
//Write some code you want to execute on UI after doInBackground() completes
return ;
}

@Override
protected void onPreExecute() {
//Write some code you want to execute on UI before doInBackground() starts
return ;
}
}

在你的 Activity 中编写这个类并调用你想要执行你的方法的地方

new AsyncTaskEx().execute();

关于android - 使特定代码在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10733682/

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