Android run thread in service every X seconds

后端 未结 4 1538
醉酒成梦
醉酒成梦 2020-12-05 01:11

I want to create a thread in an Android service that runs every X seconds

I am currently using , but the postdelayed method seems to really lag out my app.

4条回答
  •  旧时难觅i
    2020-12-05 01:53

    MyService.java

    public class MyService extends Service {
    
        public static final int notify = 5000;  //interval between two services(Here Service run every 5 seconds)
        int count = 0;  //number of times service is display
        private Handler mHandler = new Handler();   //run on another Thread to avoid crash
        private Timer mTimer = null;    //timer handling
    
        @Override
        public IBinder onBind(Intent intent) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        @Override
        public void onCreate() {
            if (mTimer != null) // Cancel if already existed
                mTimer.cancel();
            else
                mTimer = new Timer();   //recreate new
            mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            mTimer.cancel();    //For Cancel Timer
            Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
        }
    
        //class TimeDisplay for handling task
        class TimeDisplay extends TimerTask {
            @Override
            public void run() {
                // run on another thread
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // display toast
                        Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
                    }
                });
    
            }
    
        }
    }
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            startService(new Intent(this, MyService.class)); //start service which is MyService.java
        }
    }
    

    Add following code in AndroidManifest.xml

    AndroidManifest.xml

    
    

提交回复
热议问题