0

我正在练习服务,但在开始时卡住了。我希望每 3 秒从服务中出现一次祝酒词。

我在做什么

我的服务.java

package com.example.servicedemo;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class myService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub

    return null;
}

public myService() {
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Service created", 3000).show();
        }
    }, 0, 3000);



}



@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Toast.makeText(getApplicationContext(), "Sevice destroyed", 3000).show();

   }
}

日志猫。. .

08-06 22:00:55.105: E/AndroidRuntime(422):  FATAL EXCEPTION: Timer-0
08-06 22:00:55.105: E/AndroidRuntime(422):  java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-06 22:00:55.105: E/AndroidRuntime(422):  at android.os.Handler.<init>(Handler.java:121)
08-06 22:00:55.105: E/AndroidRuntime(422):  at android.widget.Toast.<init>(Toast.java:68)
08-06 22:00:55.105: E/AndroidRuntime(422):  at android.widget.Toast.makeText(Toast.java:231)
08-06 22:00:55.105: E/AndroidRuntime(422):  at com.example.servicedemo.myService$1.run(myService.java:35)
08-06 22:00:55.105: E/AndroidRuntime(422):  at java.util.Timer$TimerImpl.run(Timer.java:284)

这可能是因为计时器不适用于 UI 线程。我可以在这里使用处理程序,但问题是如何在处理程序中重复任务。请指教

4

1 回答 1

7

用这个

    public void doToast()
     {
    final Handler handler= new Handler();
    handler.postDelayed(new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Toast.makeText(context, text, duration).show();
            handler.postDelayed(this, 3000);
        }

     }, 3000);

}`

获取上下文并使用处理程序制作吐司

于 2014-08-06T16:54:56.980 回答