我使用的是在android.app.Service中定义的服务机器人。
我从一个活动中调用这个服务(myService)。
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)发布于 2012-09-19 15:54:17
你是从一个工作线程调用它的。您需要在主线程中调用Toast.makeText() (以及处理UI的大多数其他函数)。例如,您可以使用处理程序。
你需要打电话给Toast.makeText(.)在UI线程中:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});https://stackoverflow.com/questions/12498226
复制相似问题