How to set a timer in android

前端 未结 13 1702
天命终不由人
天命终不由人 2020-11-22 06:43

What is the proper way to set a timer in android in order to kick off a task (a function that I create which does not change the UI)? Use this the Java way: http://docs.ora

13条回答
  •  北海茫月
    2020-11-22 06:59

    Here we go.. We will need two classes. I am posting a code which changes mobile audio profile after each 5 seconds (5000 mili seconds) ...

    Our 1st Class

    public class ChangeProfileActivityMain extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
    
            Timer timer = new Timer();
            TimerTask updateProfile = new CustomTimerTask(ChangeProfileActivityMain.this);
            timer.scheduleAtFixedRate(updateProfile, 0, 5000);
        }
    
    }
    

    Our 2nd Class

    public class CustomTimerTask extends TimerTask {
    
        private AudioManager audioManager;
        private Context context;
        private Handler mHandler = new Handler();
    
        // Write Custom Constructor to pass Context
        public CustomTimerTask(Context con) {
            this.context = con;
        }
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
    
            // your code starts here.
            // I have used Thread and Handler as we can not show Toast without starting new thread when we are inside a thread.
            // As TimePicker has run() thread running., So We must show Toast through Handler.post in a new Thread. Thats how it works in Android..
            new Thread(new Runnable() {
                @Override
                public void run() {
                    audioManager = (AudioManager) context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
                                audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                                Toast.makeText(context, "Ringer Mode set to Normal", Toast.LENGTH_SHORT).show();
                            } else {
                                audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                                Toast.makeText(context, "Ringer Mode set to Silent", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }).start();
    
        }
    
    }
    

提交回复
热议问题