2

There are some problem! I want to do some action after a second like change the words after 5 second.I set everything as well besides the setting of timer.

I think it is easy for everyone but i just pick up android 3 days. What should i do?

noahh
  • 21
  • 2
  • http://stackoverflow.com/questions/17839419/android-thread-for-a-timer/17839725#17839725. check this might help if you use a timer use `runOnUiThread` to update textview. you can also use a handler. – Raghunandan Jul 25 '13 at 10:20

2 Answers2

1

Use a AlarmManager for repeating actions.

Example:

PendingIntent pintent = PendingIntent.getService(context, 0, new Intent(context, YourIntentHere.class), 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), iInterval, pintent);

So just encapsulate your logic you want to repeat in something wich is capable for an intent (Activity or Service).

Alternatively you could use an AsyncTask with Sleep, but I would not recommend sth like that.

See also:

http://developer.android.com/reference/android/app/AlarmManager.html http://www.techrepublic.com/blog/android-app-builder/use-androids-alarmmanager-to-schedule-an-event/

Thkru
  • 4,218
  • 2
  • 18
  • 37
0

For actions that are only done once:

bad one: start a Thread use Thread.Sleep(5000) and then make sure you are in the Ui-Thread again using myActivity.runOnUiThread(Runnable) and change the Text again

better one: Use asynctask! ->

        new AsyncTask<String, Void, Void>()
        {
            protected void onPreExecute()
            {
                // ui thread
            };

            @Override
            protected Void doInBackground(String... params)
            {
                // non ui thread
                // do your first action here
                try
                {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e)
                {
                }
                return null;
            }

            protected void onPostExecute(Void result)
            {
                // ui thread
                // do your seconds action here
            };
        }.execute("");
Thkru
  • 4,218
  • 2
  • 18
  • 37
  • Sorry, i don't understand, can u explain it more simply? – noahh Jul 26 '13 at 13:45
  • You can copy&paste this code in your app. Then you can do Logic/Operations in the "onBackground" method. Later you can display dialogs again in the "onPostExecute" – Thkru Jul 29 '13 at 10:12