我正在使用android.app.Service中定义的Service Android。
我从一个Activity调用此服务(myService)。
我的服务是:
public class myService extends Service{
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
TimerTask task = new TimerTask(){
public void run(){
Log.i("test","service running");
checkDate();
}
};
timer = new Timer();
timer.schedule(task, 0, 20000);
}
public void checkDate(){
Toast toast = Toast.makeText(this, "SIMPLE MESSAGE!", Toast.LENGTH_LONG);
toast.show();
}
}
方法checkDate()驻留在myService类中。
产生的错误是:
09-19 15:41:35.267: E/AndroidRuntime(2026): FATAL EXCEPTION: Timer-0
09-19 15:41:35.267: E/AndroidRuntime(2026): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-19 15:41:35.267: E/AndroidRuntime(2026): at android.os.Handler.<init>(Handler.java:121)
09-19 15:41:35.267: E/AndroidRuntime(2026): at android.widget.Toast$TN.<init>(Toast.java:310)
09-19 15:41:35.267: E/AndroidRuntime(2026): at android.widget.Toast.<init>(Toast.java:84)
09-19 15:41:35.267: E/AndroidRuntime(2026): at android.widget.Toast.makeText(Toast.java:226)
答案 0 :(得分:23)
TimerTask
在一个单独的线程中运行。必须从已建立Toast.makeText()
的线程执行Handler/Looper
。基本上这意味着您需要在其中运行标准Android消息/事件调度程序的线程上进行吐司。
最简单的方法是使用 checkDate()
方法:
runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(this, "SIMPLE MESSAGE!", Toast.LENGTH_LONG);
toast.show();
}
});
击> <击> 撞击>
编辑:我是个白痴,这不对。您无法从服务上下文中调用runOnUiThread()
您需要使用Handler。在您的服务中:
private Handler handler;
在您服务的onCreate()
中:
handler = new Handler();
checkDate()
方法中的:
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(myService.this, "SIMPLE MESSAGE!", Toast.LENGTH_LONG);
toast.show();
}
});
答案 1 :(得分:4)
你是从工作线程调用的。您需要从主线程中调用Toast.makeText()(以及处理UI的大多数其他函数)。例如,您可以使用处理程序。
您需要从UI线程调用Toast.makeText(...):
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});