【问题标题】:How to display toast from service on repeated interval如何以重复的时间间隔显示服务中的吐司
【发布时间】:2014-08-06 16:46:04
【问题描述】:

我正在练习服务,但一开始就卡住了。 我希望在服务后每 3 秒出现一次 toast。

我在做什么

myservice.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 线程。 我可以在这里使用处理程序,但问题是如何在处理程序中重复任务。 请指教

【问题讨论】:

  • 我也有这个问题。我所做的是使用 Otto Bus --> square.github.io/otto。它允许您通过单例在类之间进行通信。

标签: android android-service timertask android-toast


【解决方案1】:

使用这个

    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);

}`

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

【讨论】:

    猜你喜欢
    • 2013-12-20
    • 2019-11-19
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多