Приложение Android закрывается принудительно при отправке более 100 текстовых сообщений

1

Я пытаюсь отправить текстовое сообщение определенное количество раз, как бы то ни было, когда я делаю что-либо более 100, это принудительно закрывает приложение. Какие-либо предложения?

Итак, вот мой обновленный код, с несколькими дополнительными проблемами сейчас - тост НИКОГДА не исчезнет, и если я включу свои операторы if для проверки данных, это не сработает (в основном, чтобы попросить пользователя ввести информацию, если это null вместо просто закройте приложение)

Вот мой обновленный код:

package net.learn2develop.SMS;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText PhNumber, Message, TxtCount;
Button btnSendSMS;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //create text box to enter phone number
    PhNumber=(EditText) findViewById(R.id.PhNumber);

    //create text box to enter message
    Message=(EditText) findViewById(R.id.Message);

    //create text box to see how many times the user wants to send message
    TxtCount=(EditText) findViewById(R.id.TxtCount);

    //create button to send text message
    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
    //create listener for button
    btnSendSMS.setOnClickListener(new View.OnClickListener()

    {               
        public void onClick(View v)
            {           
                //variable for count.
                int count = 1;
                //variable for text message
                String msg = Message.getText().toString();
                //variable for phone number
                String num = PhNumber.getText().toString();
                //variable for the amount of text messages to send.
                int max = Integer.parseInt(TxtCount.getText().toString());
                //variable to watch button and hide keyboard
                InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                //test to see if count has any value at all
                //if (TxtCount.getText().toString().equals(""))
                //{
                //  Toast.makeText(getBaseContext(), "Please enter a number of times to nuke!", Toast.LENGTH_SHORT).show();
                //  return;
                //}
                //test to see if number has a value
                //else if (num.equals(""))
                //{
                //  Toast.makeText(getBaseContext(), "Please enter a phone number to nuke!", Toast.LENGTH_SHORT).show();
                //  return;
                //}
                //test to see if there is a message
                //else if (msg.equals(""))
                //{
                //  Toast.makeText(getBaseContext(), "Please enter a message!", Toast.LENGTH_SHORT).show();
                //  return;
                //}             

                //if all fields have valid data -- send text message until count = max                      
                while (count <= max) {                  
                    sendSMS(num, msg);
                    count++;
                };
                //hide the keyboard
                mgr.hideSoftInputFromWindow(TxtCount.getWindowToken(), 0);
                mgr.hideSoftInputFromWindow(PhNumber.getWindowToken(), 0);
                mgr.hideSoftInputFromWindow(Message.getWindowToken(), 0);
                //set phone number to ""
                PhNumber.setText("");
                //set message to ""
                Message.setText("");
                //set count to ""
                TxtCount.setText("");
                //refocus on phone number
                PhNumber.requestFocus();                    
            }           
    });        
}

//sends a sms message to another device
private void sendSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);

        //when the sms has been sent
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS Nuked!", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break; 
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS Nuked!",
                                    Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }
}
  • 0
    Вы, вероятно, не должны использовать устройство Android для массовых текстовых сообщений.
  • 0
    Почему вы отправляете 100 текстовых сообщений подряд?
Показать ещё 4 комментария
Теги:

2 ответа

0

Возможно, попробуйте разбить сообщения или отправить их по таймеру вместо цикла, вы можете попробовать что-то вроде этого:

               Thread background = new Thread (new Runnable() {
               public void run() {
                   Thread.sleep(100);
                           // Send message
               }
            });
0

Вероятно, вам следует организовать услугу для отправки широковещательной рассылки, когда каждое сообщение было отправлено (или не выполнено), и только затем отправить следующий. Вероятно, вы заманиваете службу, которая вызывает силовую силу.

Проверьте документы о том, как использовать "отправленное намерение".

  • 0
    Да, я добавил намерение, я опубликую свой обновленный код.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню