Доброе утро, спасибо и извините за мой английский!
Я работаю в приложении для Android, я хочу, чтобы приложение отправляло много смс с помощью SmsManager. Это нормально, но проблема в том, что когда я пытаюсь реализовать любой тип связи между отправкой каждого смс. Я пытался с Thread внутри for, asynctask тоже, но приложение тоже засыпает, и мне нужно, чтобы приложение не блокировалось, пока я отправляю смс.
Я читаю номера внешнего(внутри каталога приложения), затем я помещаю эти данные в HashTable и выполняю цикл for для вызова функции SmsManager sendTextMessage.
MainActivity.java
package com.example.howtosendsmsinandroid;
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.AsyncTask;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
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.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity{
Button btn;
//EditText et1,et2;
private static final int Request_Read_Contacts=0;
private static final int Request_Code_permission=2;
BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;
public void onResume() {
super.onResume();
smsSentReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS has been sent", 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;
default:
break;
}
}
};
smsDeliveredReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
switch(getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));
}
public void onPause() {
super.onPause();
unregisterReceiver(smsSentReceiver);
unregisterReceiver(smsDeliveredReceiver);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//et1=(EditText)findViewById(R.id.number);
//et2=(EditText)findViewById(R.id.Content);
String cPermission= Manifest.permission.SEND_SMS;
try{
if (ActivityCompat.checkSelfPermission(this,cPermission)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{cPermission},Request_Code_permission);
}
}
catch(Exception e){
e.printStackTrace();
}
String sPermission= Manifest.permission.INTERNET;
try{
if (ActivityCompat.checkSelfPermission(this,sPermission)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{cPermission},Request_Code_permission);
}
}
catch(Exception e){
e.printStackTrace();
}
}
public void onmessage(View v){
//String phonenumber = et1.getText().toString();
//String msg = et2.getText().toString();
try
{
Hashtable<Integer, ArrayList<String>> contacts = new Hashtable<Integer, ArrayList<String>>();
String linea;
InputStream fraw =
getResources().openRawResource(R.raw.numbers);
BufferedReader brin =
new BufferedReader(new InputStreamReader(fraw));
int count = 0;
while ((linea = brin.readLine()) != null){
//NO ENVIA SI SON 160 O MAS CARACTERES (DE FORMA ORDINARIA)
String[] parts = linea.split(";");
contacts.get(count);
ArrayList<String> numbers = new ArrayList<String>();
numbers.add(parts[0]);
numbers.add(parts[1]);
numbers.add(parts[2]);
contacts.put(count, numbers);
count++;
}
int i = 0;
for (Map.Entry<Integer, ArrayList<String>> entry: contacts.entrySet()){
SmsManager sms = SmsManager.getDefault();
String number = entry.getValue().get(0);
String nom = entry.getValue().get(1);
String animal = entry.getValue().get(2);
String msg = "Hola {{NOMBRE}}, le informamos que su {{ANIMAL}} se ha comido a su vecina. Contacte con nosotros a traves de www.porncharacters.com";
msg = msg.replace("{{NOMBRE}}", nom);
msg = msg.replace("{{ANIMAL}}", animal);
PendingIntent piSent=PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
PendingIntent piDelivered=PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
/*
Toast.makeText(getApplicationContext(), "Numero:" + number,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Message: " + msg,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Numero: " + number,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Numero: " + nom,
Toast.LENGTH_LONG).show();
*/
sms.sendTextMessage(number, null, msg, piSent, piDelivered);
i++;
//Thread.sleep(60000);
}
fraw.close();
}
catch (Exception ex)
{
Log.e("Ficheros", "Error al leer fichero desde recurso raw");
}
}
}