[英]How to display toast from service on repeated interval
我正在练习服务,但始终处于起步阶段。 我希望每隔3秒从服务中出现一次吐司。
我在做什么
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。 。 。
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线程。 我可以在这里使用处理程序,但问题是如何在处理程序中重复执行任务。 请指教
用这个
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);
}`
获取上下文并使用处理程序进行烤面包
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.