7

I have this method

public void GetSMS(){
       //in this method I read SMS in my app inbox,
       //If have new SMS create notification
}

for this I think create timer tick method and every 5 sec call GetSMS()

How can I create a correct method for that ?

android
  • 101
  • 1
  • 1
  • 7

5 Answers5

17

Here is an example of Timer and Timer Task. Hope this helps.

final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                // Do whatever you want
            }
        });
    }
};
timer.schedule(timerTask, 1000); // 1000 = 1 second.
Farooq Arshed
  • 1,984
  • 2
  • 17
  • 26
  • 1
    :I called my receiveMessage method inside of the run() block but it does not being invoked every 1 second!would you please help me on this issue? –  Jul 01 '14 at 07:25
5

Maybe with a timer and a timertask?

See javadocs: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html

Yet receiving broadcasts is probably a more solid solution. See: Android - SMS Broadcast receiver

Community
  • 1
  • 1
Nicklas Gnejs Eriksson
  • 3,395
  • 2
  • 21
  • 19
5

Use Timer.scheduleAtFixedRate() as follow:

final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                GetSMS();
            }
        });
    }
};

timer.scheduleAtFixedRate(timerTask, 5000, 5000); // every 5 seconds.
geek
  • 346
  • 6
  • 14
1

I saw it by accident.. This is not the right way to do it..

You don't need to check if there is a sms that received. Android provide broadcast receiver to get notified when sms is income.

Here you go, you have the link here.. Copy paste and it will work great

http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87

Hope that this make sense

Aviad
  • 1,539
  • 1
  • 9
  • 24
1

Although the above timer methods are the correct way to use timers of the sort you are after, I quite like this little hack:

new CountDownTimer(Long.MAX_VALUE, 5000)
{
    public void onTick(long millisUntilFinished)
    {
        // do something every 5 seconds...
    }

    public void onFinish()
    {
       // finish off when we're all dead !
    }
}.start();

Long.MAX_VALUE has, according the Java docs, a (signed) value of 2^63-1, which is around 292471 millennia ! So starting up one of these countdown timers effectively lasts forever relatively speaking. Of course this depends on your interval time. If you want a timer every 1 second the timer would "only" last 58494 millenia, but we don't need to worry about that in the grander scheme of things.