如何显示从服务上重复间隔吐司 [英] How to display toast from service on repeated interval
本文介绍了如何显示从服务上重复间隔吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我练的服务,但卡在开始。
我想,一个面包从服务每3秒后出现。
I'm practicing services, but stuck on beginning. I want that a toast appears after every 3 sec from a service.
什么肌内做
myservice.java
myservice.java
package com.example.servicedemo;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class myService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public myService() {
// TODO Auto-generated constructor stub
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service created", 3000).show();
}
}, 0, 3000);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getApplicationContext(), "Sevice destroyed", 3000).show();
}
}
logcat中。 。 。
logcat. . .
08-06 22:00:55.105: E/AndroidRuntime(422): FATAL EXCEPTION: Timer-0
08-06 22:00:55.105: E/AndroidRuntime(422): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-06 22:00:55.105: E/AndroidRuntime(422): at android.os.Handler.<init>(Handler.java:121)
08-06 22:00:55.105: E/AndroidRuntime(422): at android.widget.Toast.<init>(Toast.java:68)
08-06 22:00:55.105: E/AndroidRuntime(422): at android.widget.Toast.makeText(Toast.java:231)
08-06 22:00:55.105: E/AndroidRuntime(422): at com.example.servicedemo.myService$1.run(myService.java:35)
08-06 22:00:55.105: E/AndroidRuntime(422): at java.util.Timer$TimerImpl.run(Timer.java:284)
也许这是因为定时器不工作在UI线程。
我可以在这里使用的处理程序,但疑问句是如何重复任务的处理程序。
请告知
Possibly this is because timer doesn't works on UI thread. I can use handler here but the ques is how to repeat task in handler. Please advise
推荐答案
使用此
public void doToast()
{
final Handler handler= new Handler();
handler.postDelayed(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, text, duration).show();
handler.postDelayed(this, 3000);
}
}, 3000);
}`
获取上下文,并使用一个处理程序,使面包
Get a context and use a handler to make toast
这篇关于如何显示从服务上重复间隔吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文