0

I want to call a thread in android activity after a time interval like 5 or 10 mins. after that i want to send an automatic SMS in android, to any number. Please help me. I have idea about thread that we can do with this but the problem with that function is, it is calling over and over again. Thanks in advance

Its just that code. But it once calls, then sends sms repeatedly until we stop application. Please help me.

Thread timer = new Thread() 
        {
            @Override
            public void run() 
            {
                try 
                {

                    sleep(1000*60*2);

                } 
                catch (InterruptedException ex) 
                {
                    ex.printStackTrace();
                } 
                finally 
                {
                    String phone_number = "123456789"; // some phone number here
                    String text = 
                            "Hello this is an automatic SMS service informing you about the current status: \n" +
                            " City :" +cityName +"\n"
                            +"State :"     +stateName+"\n"
                            +"Country :"   +countryName +"\n";

                    SmsManager smsMgr = SmsManager.getDefault();
                    smsMgr.sendTextMessage(phone_number, "Hussnain Muavia", text, null, null);
                    txtLat.setText("SMS Sent");

                }
            }
        };
        timer.start();  
  • Where is the rest of your code. You are doing something wrong and while answers here may help you achieve your ultimate goal, you will likely make the same mistake again somewhere else. – iheanyi Dec 12 '14 at 21:42

3 Answers3

0

I would use a Timer with a TimerTask:

TimerTask myTimerTask = new TimerTask() {

    public void run() {
    //do your code here
    }
};

Timer myTimer = new Timer();

myTimer.schedule(myTimerTask, when you want to start?[im milliseconds for example], 300000[5mins]);

And if you don't want to execute the TimerTask again simply call. myTimer.cancel();

Notice Don't Forget to call myTimer.cancel(); in your onPause because otherwise the timer will continue executing and this Drains battery!

Update regarding your comment myTimer.schedule can take various Parameters. Interesting for you are this one:

myTimer.schedule(Runnable r, When to first execute, In which Interval);

Runnable r is your TimerTask which will be executed after When to first execute expired. If you want to start immediatly, simply pass 0. In which Interval if you put in there 50, then your TimerTask will be execute every 50ms, after When to first execute expired.

This should do the trick.

Hope it helps! ;)

Mike
  • 857
  • 1
  • 7
  • 11
  • Thanks Mike, but would you tell me please about the parameters of schedule()..?? – Hussnain Muavia Dec 12 '14 at 21:11
  • @HussnainMuavia i've updated my question. Please mark as accepted as it is the solution for your issue. :) – Mike Dec 12 '14 at 21:16
  • @HussnainMuavia no you are missunderstanding me. Look to the top of my answere and move with your eyes to the left. There's a White check mark. Click it :) – Mike Dec 12 '14 at 21:23
  • Never use a `Timer` in Android. – Kevin Krumwiede Dec 12 '14 at 21:36
  • 1
    @KevinKrumwiede First of all, it would be nice from your side if don't just downvote an answere, without providing some arguments...Secondly i'm not sure but i think you should write an e-mail to Google. They don't say anything about "Never use a `Timer` in Android! http://developer.android.com/reference/java/util/Timer.html ... hmmm – Mike Dec 12 '14 at 21:44
  • @Mike A lot has been written about this. http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/ – Kevin Krumwiede Dec 12 '14 at 21:53
  • @Mike Everyone should know by now that you shouldn't use `Timer` in Android. Anyone who doesn't can Google for an explanation. This answer also explains a little: http://stackoverflow.com/questions/4597690/android-timer-how But it's not just the UI that you can't touch from a `Timer`. You cannot touch data from any other thread without explicit synchronization. To understand this, you need to understand the Java Memory Model, which is far too complex to explain in a comment. – Kevin Krumwiede Dec 12 '14 at 21:59
0

Do it in Android way. Use AlarmManager to set repeated actions, then create custom BroadcastReceiver to perform specific action. This is example how to implement. It is more complex but it is more reliable and android nature way.

Robertas Setkus
  • 3,075
  • 6
  • 31
  • 54
0

You want to use AlarmManager, that's the Android way. Everything else you will run into trouble. Do not use Handler.postDelayed because the callback will be dropped if the Looper exits before the timer is up:

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped

Creating an alarm is easy.

AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
long FIVE_MINS_IN_MILLIS = 1000 * 60 * 5;
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), FIVE_MINS_IN_MILLIS , pi); 
browep
  • 5,057
  • 5
  • 29
  • 37
  • You would normally use the UI thread's Looper, and if that's exiting, then so is your program. – Kevin Krumwiede Dec 13 '14 at 00:10
  • not true. "exiting" does not mean that the program was shut down. It may mean that the OS needs more memory and the program state was saved. It will still show up in recent apps and I am assuming that you still want your callback run – browep Dec 15 '14 at 16:37
  • I suppose whether you should use a `Handler` or an alarm depends on whether the lifetime of the thing you want to run at intervals is logically bounded by the lifecycle of the activity, or exists outside an activity. Kind of like how you typically use `AsyncTask` for background tasks that live inside one activity, and `Service` for things that outlive activities. – Kevin Krumwiede Dec 15 '14 at 21:49