我是android的新手。 我用服务和线程创建了一个应用程序,每隔5秒显示一次Toast:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
Handler mHandler = new Handler();
@Override
public void onCreate() {
super.onCreate();
final Runnable RunnableUpdateResults = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Hello", Toast.LENGTH_SHORT).show();
}
};
new Thread() {
public void run() {
try {
mHandler.postDelayed(RunnableUpdateResults);
sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();}
}
}.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
public void onStart(final Context context,Intent intent, int startId)
{
}
}
但我的Toast只显示一次。没有崩溃。 为此,我使用了Handler的postDelayed函数。它将在主UI线程上以指定的延迟运行您的代码,因此您将能够更新UI控件,但它也不起作用。
重复执行任务的任何解决方案?
答案 0 :(得分:1)
在循环中调用Thread.sleep
,然后循环为:
boolean isThreadRunning=true;
new Thread() {
public void run() {
try {
while(isThreadRunning){
mHandler.postDelayed(RunnableUpdateResults);
sleep(5000);
}
} catch (InterruptedException e) {e.printStackTrace();}
}
}.start();
停止线程制作isThreadRunning=false;
您可以使用handler.postDelayed
mHandler.postDelayed(RunnableUpdateResults,5000);
并在RunnableUpdateResults
中调用mHandler.postDelayed:
final Runnable RunnableUpdateResults = new Runnable() {
public void run() {
mHandler.postDelayed(RunnableUpdateResults,5000);
Toast.makeText(getBaseContext(),
"Hello", Toast.LENGTH_SHORT).show();
}
};
停止处理程序调用{{1}}方法:
removeCallbacks
答案 1 :(得分:0)
将Timer
与TimerTask
new Timer().schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(RunnableUpdateResults);
}
}, 0, 5000);