CL So
CL So

Reputation: 3759

Android, run some lines of code at specified time

view.findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        EditText input=(EditText)parent.findViewById(R.id.input);

        //run at specified time
        Toast.makeText(getApplicationContext(), input.getText().toString(), Toast.LENGTH_SHORT).show();
        //run at specified time

    }
});

I know there are two ways to do that

First is handler, but it does not work when device sleep

Second is AlarmManager, but it must create another activity or service

I just want to run a piece of code and these codes have many dependency to the current activity, is there any other way to run the code at specified time?

Upvotes: 2

Views: 178

Answers (1)

Hardik Dungrani
Hardik Dungrani

Reputation: 119

For run some lines of code at specified time you need to user Timer class of android.Use Timer class not Countdown Timer class.

Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            //your lines of code at specified time

        }
    }, delays Millisecond, Interval Millisecond);
  • delay in millisecond means Timer start after this millisecond

  • interval millisecond means Timer run at this specific time every time.

Upvotes: 2

Related Questions