Java 在服务中以特定间隔运行toast
我正试着在服务结束后每隔2秒敬酒一次。 这段普通代码工作正常。这只是一个测试,以显示吐司Java 在服务中以特定间隔运行toast,java,android,multithreading,service,handler,Java,Android,Multithreading,Service,Handler,我正试着在服务结束后每隔2秒敬酒一次。 这段普通代码工作正常。这只是一个测试,以显示吐司 public int-onstart命令(Intent-Intent、int-flags、int-startId){ //让它继续运行直到停止。 新线程(新ToastRunner(this)).start(); 返回开始时间; }像这样试试 @Override public void run() { try { // preparing a looper on current thread
public int-onstart命令(Intent-Intent、int-flags、int-startId){
//让它继续运行直到停止。
新线程(新ToastRunner(this)).start();
返回开始时间;
}
像这样试试
@Override
public void run() {
try {
// preparing a looper on current thread
// the current thread is being detected implicitly
Looper.prepare();
// now, the handler will automatically bind to the
// Looper that is attached to the current thread
// You don't need to specify the Looper explicitly
handler = new Handler();
// After the following line the thread will start
// running the message loop and will not normally
// exit the loop unless a problem happens or you
// quit() the looper (see below)
Looper.loop();
}
catch (Throwable t) {
Log.e(TAG, "halted due to an error", t);
}
}
试试这个代码
while (true) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Service Started", Toast.LENGTH_SHORT).show();
}
});
Thread.sleep(2000);
}
这意味着您不能从另一个线程访问ui元素。你必须使用uiThred。试试这个代码
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Service Started", Toast.LENGTH_SHORT).show();
Thread.sleep(2000);
}
}
}
这对我没什么帮助。我需要更多的详细说明。我不知道为什么会出现负面反应。但这段代码按预期工作。非常感谢。唯一的问题是,即使服务被破坏,它仍会继续运行。然后在服务的onDestroy()中中断线程。即,。onDestroy(){thead.interrupt();}ok使用一个布尔变量修复了它while(isRunning){new Handler(Looper.getMainLooper()).post(new Runnable(){@Override public void run(){Toast.makeText(上下文,“服务已启动”,Toast.LENGTH_SHORT).show();}});Thread.sleep(2000);}`