[Solved] How do i stop loop


First problem you would have with the current code is that once you have clicked the button it would result in lot of messages being sent even before user realizes that he sent that many messages, you need to induce a delay between each message.

The next problem is that your app could hang as your app would be executing the infinite loop of sending messages, executing the code in separate thread will help.

To resolve these two issues, you have to put the sending sms code in a new thread(use AsyncTask for that) and induce a delay after each message is sent and after the delay check if the stop button is clicked.

Below is the code for doing this:

class SendSMS extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                while (!dostop) { //if stop button is clicked stop the loop
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(phoneNo, null, message, null, null);
                    Toast.makeText(getApplicationContext(), +i + " SMS Remaining", Toast.LENGTH_LONG).show();                        Thread.sleep(5000);
                }
            } catch (Exception e) {

            }
            return null;
        }
    }

Usage: Call the above code after the send sms button is clicked.

send.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dostop = false; //set to false first
                                        new SendSMS().execute();
                                    }
                                }
        );

When the stop button is clicked you need to set a variable dostop=true.

stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dostop = true;
            }
        });

Also I suggest adding some UI to show the count of sms sent.

1

solved How do i stop loop