Android Timer within a service

前端 未结 2 1174

I am having problems running a timer in a service I have created. The task that the timer calls simply isn\'t called. I know that the service starts as I have put toasts wit

相关标签:
2条回答
  • 2020-12-02 09:45

    Thanks, I also needed to cancel the timer ..

    public void onDestroy() {
            timer.cancel();
            Toast.makeText(this, "ServiceTalkGeology stopped.", 
            Toast.LENGTH_SHORT).show();
            super.onDestroy();
    }
    
    0 讨论(0)
  • 2020-12-02 10:05

    Android does not allow UI events like Toasts from outside the main thread. The run is getting called, but the Toast is being ignored.

    To create the Toast on the UI thread, you can use a Handler and an empty Message like so:

    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();
            }
        };    
    }
    
    0 讨论(0)
提交回复
热议问题