Leo*_*nto 13 service android countdown
我有服务.并且有一个名为onServiceUpdate()的方法.此方法类似于Google Maps API中的onLocationChanged().
所以我想在onServiceUpdate()方法中启动CountDownTimer,但显示如下错误:
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)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
@Override
public void onServiceUpdate(ServiceState state)
{
final float[] distance = new float[2];
Location.distanceBetween(state.getGeoPoint().getLatitude(), state.getGeoPoint().getLongitude(), 6.130607787619352,106.81839518499267, distance);
if (distance[0] > 25.0)
{
CountDownTimer cdt5 = new CountDownTimer(total_onServiceUpdate,1000) {
@Override
public void onTick(long millisUntilFinished) {
total_onServiceUpdate = millisUntilFinished/1000;
}
@Override
public void onFinish() {
sendSMS();
stopSelf();
}
}.start();
}
Run Code Online (Sandbox Code Playgroud)
Ell*_*ltz 24
onServiceUpdate()是一个运行并通知你的aysnchronous任务,因此它是一个后台线程.你需要做的就是调用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();
}
});
Run Code Online (Sandbox Code Playgroud)
现在你可以继续了.始终通过主Looper上的屏幕调用代码调情
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
8955 次 |
| 最近记录: |