Android Can';t在CountDownTimer中未调用Looper.prepare()的线程内创建处理程序
我有服务。还有一个名为onServiceUpdate()的方法。此方法与Google Maps API中的onLocationChanged()类似 所以我想在onServiceUpdate()方法中启动倒计时,但显示如下错误:Android Can';t在CountDownTimer中未调用Looper.prepare()的线程内创建处理程序,android,service,countdown,Android,Service,Countdown,我有服务。还有一个名为onServiceUpdate()的方法。此方法与Google Maps API中的onLocationChanged()类似 所以我想在onServiceUpdate()方法中启动倒计时,但显示如下错误: Can't create handler inside thread that has not called Looper.prepare() java.lang.RuntimeException: Can't create handler inside thr
Can't create handler inside thread that has not called Looper.prepare()
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.os.CountDownTimer$1.<init>(CountDownTimer.java:114)
at android.os.CountDownTimer.<init>(CountDownTimer.java:114)
at skripsi.ubm.studenttracking.Service2$6.<init>(Service2.java:317)
at skripsi.ubm.studenttracking.Service2.onServiceUpdate(Service2.java:317)
我认为问题在于,在sendSMS()中,您试图执行一些需要UIThread的操作(例如更新视图)。 试试这个:
Handler mHandler = new Handler() {
public void handleMessage(Message msg){
sendSMS();
}};
将onFinish方法修改为
@Override
public void onFinish() {
mHandler.sendEmptyMessage(0);
stopSelf();
}
无法通过处理程序从服务更新活动gui,因为必须在gui线程中创建该处理程序 相反,您必须从您的服务开始,在获取此广播的活动中实现一个本地线程。onServiceUpdate()是一个运行并通知您的AYSN同步任务,因此它是一个后台线程。您只需调用timer.start();从主线程来看,服务实际上是在主线程上运行的,而intentService并不是这样,您的解决方案是
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
CountDownTimer cdt5 = new CountDownTimer(total_onServiceUpdate,1000) {
@Override
public void onTick(long millisUntilFinished) {
total_onServiceUpdate = millisUntilFinished/1000;
}
@Override
public void onFinish() {
sendSMS();
stopSelf();
}
}.start();
}
});
现在你可以继续了,先生。始终使用屏幕上的调情代码
希望它能帮助Android:
请在调用处理程序之前尝试此操作
如果(Looper.MyLooper()==null){Looper.Prepare();}在
cdt.start()之后抛出错误。它不会在onFinish()
方法中执行任何操作。我认为问题可能在于在每个onTick
中更改millisInFuture
的值,这非常有帮助。还有一个问题。我想在该处理程序中停止self(),但它不起作用。你能帮帮我吗?服务没有停止?我们可以尝试TheNameOfYourService.this.stopSelf()
如果没有,请尝试stopService(newintent(getApplicationContext(),TheNameOfYourService.class))它们是不同的杀猫方法。如果它仍然不让我了解你的服务@LeonardFebrianto,如果你的任务通过评论、投票或勾号解决了,也请告诉我。。如果我在一个循环完成后创建一个新的处理程序,这是很糟糕的。假设每10秒我创建一个新的处理程序,完成后我创建一个新的处理程序。@kataroty我不理解你的问题,你的意思是在循环中还是在循环中意味着循环器?@Elltz很抱歉把问题写得不好。但我的意思是在循环
的每次迭代中创建新的循环器
。这对性能有多差?
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
CountDownTimer cdt5 = new CountDownTimer(total_onServiceUpdate,1000) {
@Override
public void onTick(long millisUntilFinished) {
total_onServiceUpdate = millisUntilFinished/1000;
}
@Override
public void onFinish() {
sendSMS();
stopSelf();
}
}.start();
}
});