服务中的Android Timer

时间:2010-09-29 07:46:46

标签: android

我在创建的服务中运行计时器时遇到问题。定时器调用的任务不会被调用。我知道服务开始,因为我已经在其中放置了toast并且它们被调用,但是当它们在计时器内时不会被调用。帮助赞赏。

服务类:

public class LocalService extends Service
{
    private static Timer timer = new Timer(); 
    private Context ctx;

    public IBinder onBind(Intent arg0) 
    {
          return null;
    }

    public void onCreate() 
    {
          super.onCreate();
          ctx = this; 
          startService();
    }

    private void startService()
    {           
        timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
    }

    private class mainTask extends TimerTask
    { 
        public void run() 
        {
            Toast.makeText(ctx, "test", Toast.LENGTH_SHORT).show();
        }
    }    

    public void onDestroy() 
    {
          super.onDestroy();
          Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
    }    
}

主要课程:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    startService(new Intent(RingerSchedule.this, LocalService.class));      
}   

2 个答案:

答案 0 :(得分:52)

Android不允许主线程外部的Toasts等UI事件。正在调用run,但是Toast被忽略了。

要在UI线程上创建Toast,您可以使用Handler和空消息,如下所示:

public class LocalService extends Service
{
    private static Timer timer = new Timer(); 
    private Context ctx;

    public IBinder onBind(Intent arg0) 
    {
          return null;
    }

    public void onCreate() 
    {
          super.onCreate();
          ctx = this; 
          startService();
    }

    private void startService()
    {           
        timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
    }

    private class mainTask extends TimerTask
    { 
        public void run() 
        {
            toastHandler.sendEmptyMessage(0);
        }
    }    

    public void onDestroy() 
    {
          super.onDestroy();
          Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
    }

    private final Handler toastHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
        }
    };    
}

答案 1 :(得分:1)

谢谢,我还需要取消计时器..

public void onDestroy() {
        timer.cancel();
        Toast.makeText(this, "ServiceTalkGeology stopped.", 
        Toast.LENGTH_SHORT).show();
        super.onDestroy();
}