Sin*_*ich 3 android background
我想让这个代码在后台运行.我无法弄清楚如何创建服务或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();
}
Run Code Online (Sandbox Code Playgroud)
这是代码片段 AsyncTask
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 ;
}
}
Run Code Online (Sandbox Code Playgroud)
将此类写入您的内部Activity并调用您想要执行方法的位置
new AsyncTaskEx().execute();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3773 次 |
| 最近记录: |