Android 准备问题
我试图在计时器内循环祝酒,但祝酒词没有显示出来 logcat中的日志显示,无法在未调用looper.prepare()的线程内创建处理程序。我不确定这是什么意思Android 准备问题,android,Android,我试图在计时器内循环祝酒,但祝酒词没有显示出来 logcat中的日志显示,无法在未调用looper.prepare()的线程内创建处理程序。我不确定这是什么意思 int initialDelay = 10000; int period = 10000; final Context context = getApplicationContext(); TimerTask task = new TimerTask() { public voi
int initialDelay = 10000;
int period = 10000;
final Context context = getApplicationContext();
TimerTask task = new TimerTask()
{
public void run()
{
try
{
if (a != "")
{
Toast toast = Toast.makeText(context, "Alert Deleted!", Toast.LENGTH_SHORT);
toast.show();
}
}
catch (Exception e)
{
}
}
};
timer.scheduleAtFixedRate(task, initialDelay, period);
我的应用程序每10秒检查一个变量是否为空。如果它是空的,那么它将显示一个祝酒词
我在服务类中这样做没有问题,但是当我尝试在
public void onCreate(Bundle savedInstanceState)
我收到这个错误,您正在从工作线程调用它。您需要从主线程内调用Toast.makeText()(以及处理UI的大多数其他函数)。例如,您可以使用处理程序 看看这个答案
您也可以用其他方式展示这片土司
class LooperThread extends Thread {
public Handler mHandler;
@Override
public void run() {
Looper.prepare();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
现在,正如您所看到的,这个处理程序是在普通线程中创建的,所以如果您尝试从它发送任何消息,它将抛出一个异常,通过将它与Looper.prepare()和Looper.loop()绑定,您可以在UI线程中执行它内的任何语句
另一个例子
Looper允许在单个线程上顺序执行任务。处理器定义了我们需要执行的任务。这是我试图在示例中说明的一个典型场景:
class SampleLooper {
@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);
}
}
}
现在我们可以在一些其他线程(比如ui线程)中使用处理程序将任务发布到Looper上执行
handler.post(new Runnable()
{
public void run() {`enter code here`
//This will be executed on thread using Looper.`enter code here`
}
});
在UI线程上,我们有一个隐式循环器,允许我们在UI线程上处理消息