如何使用服务向多个号码发送消息?

时间:2016-10-05 06:01:29

标签: java android service smsmanager

我想向多个号码发送消息。我试过使用短信管理器。但它不起作用。

我正在onPostExecute执行AsyncTask方法。但我想创建一个服务并从该服务发送消息,因为用户可以在消息发送完成之前关闭应用程序,因此它应该在后台工作。

我创建了一个数字的arraylist。现在我要发送到服务并向每个号码发送消息。

我的尝试:

@Override
public void doPostExecute(JSONArray response) throws JSONException {

    ArrayList<String> numbers = new ArrayList<>();

    for (int i = 0; i < response.length(); i++) {

        JSONObject subObject1 = response.getJSONObject(i);

        String status = subObject1.getString("status");

        if (status.equals("1")) {

            JSONObject invitation = subObject1.getJSONObject("invitation");

            String number = invitation.getString("invitee_no");

            numbers.add(number);
        } else {

        }
    }

    try {
        SmsManager sms = SmsManager.getDefault();
        PendingIntent sentPI;
        String SENT = "SMS_SENT";

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

        sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
        sms.sendTextMessage("8655864341", null, "Hi,add me to your unique contact list.",sentPI, null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

我已经在清单中添加了发送短信的权限。

<uses-permission android:name="android.permission.SEND_SMS"/>

我该怎么做?有人可以帮忙吗?谢谢..

编辑:

我尝试编写如下服务:

    public class MessageService extends Service {

    ArrayList<String>  numbers = new ArrayList<>();
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        numbers = intent.getStringArrayListExtra("numbers");

        for(int i=0;i<numbers.size();i++) {

            sendMsg(numbers.get(i));
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void sendMsg(final String num){
        String SENT = "SMS_SENT";
        final SmsManager sms = SmsManager.getDefault();
        final PendingIntent sentPI = PendingIntent.getBroadcast(MessageService.this, 0,new Intent(SENT), 0);
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                sms.sendTextMessage("8655864341", null, "Hi MyApp SMS", sentPI, null);
            }
        }, 2000);
    }

    @Override
    public IBinder onBind(Intent intent)
    {

    //    numbers = intent.getStringArrayListExtra("numbers");

        return null;
    }
}

从活动中调用它:

       Intent serviceIntent = new Intent(this,MessageService.class);
    serviceIntent.putStringArrayListExtra("numbers",numbers);
    startService(serviceIntent);

在清单中添加了服务:

<uses-permission android:name="android.permission.SEND_SMS" />
<receiver android:name=".SmsSentReceiver"/> <receiver android:name=".SmsDeliveredReceiver"/>

<service android:name=".helper.MessageService"></service>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Activities.MainActivity" />

但是当我调试和检查服务时没有被调用。

出了什么问题?

编辑:

用广播接收器尝试这种方式:

public class MessageService extends Service {

ArrayList<String>  numbers = new ArrayList<>();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    numbers = intent.getStringArrayListExtra("numbers");

    for (String number:numbers) {


        sendSMS("8655864341","Hello");
    }


      //  sendMsg(numbers.get(i));


    return super.onStartCommand(intent, flags, startId);
}

public void sendMsg(final String num){
    String SENT = "SMS_SENT";
    final SmsManager sms = SmsManager.getDefault();
    final PendingIntent sentPI = PendingIntent.getBroadcast(MessageService.this, 0,new Intent(SENT), 0);
    Handler h = new Handler();
    h.postDelayed(new Runnable() {
        @Override
        public void run() {
            sms.sendTextMessage("7303668514", null, "Hi MyApp SMS", sentPI, null);
        }
    }, 2000);
}

@Override
public IBinder onBind(Intent intent)
{

//    numbers = intent.getStringArrayListExtra("numbers");

    return null;
}

private void sendSMS (String phoneNumber, String message){
    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
    PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(getApplicationContext(), SmsSentReceiver.class), 0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(getApplicationContext(), SmsDeliveredReceiver.class), 0);
    try {
        SmsManager sms = SmsManager.getDefault();
        ArrayList<String> mSMSMessage = sms.divideMessage(message);
        for (int i = 0; i < mSMSMessage.size(); i++) {
            sentPendingIntents.add(i, sentPI);
            deliveredPendingIntents.add(i, deliveredPI);
        }
        sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
                sentPendingIntents, deliveredPendingIntents);

    } catch (Exception e) {

        e.printStackTrace();
        Toast.makeText(getBaseContext(), "SMS sending failed...", Toast.LENGTH_SHORT).show();
    }

}


public class SmsDeliveredReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context, "SMS delivered", Toast.LENGTH_SHORT).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(context, "SMS not delivered", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

public class SmsSentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context, "SMS Sent", Toast.LENGTH_SHORT).show();

                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context, "SMS generic failure", Toast.LENGTH_SHORT)
                        .show();

                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(context, "SMS no service", Toast.LENGTH_SHORT)
                        .show();

                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(context, "SMS null PDU", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(context, "SMS radio off", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

获得此例外:

   java.lang.RuntimeException: Unable to instantiate receiver com.example.siddhi.contactsapp.helper.MessageService$SmsSentReceiver: java.lang.InstantiationException: class com.example.siddhi.contactsapp.helper.MessageService$SmsSentReceiver has no zero argument constructor

没有收到消息..

2 个答案:

答案 0 :(得分:1)

您可以这样做:

为您的Numbers列表使用for循环,并在使用处理程序内部保持每个已发送消息之间的时间间隔,例如2秒并发送消息。

OR

您可以在服务中定义广播接收器,它将检查消息传递报告,如果已传送,则发送另一条消息。

First Link

Second Link

希望它有助于:)

修改:

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {

    ArrayList<String> numberlist=new ArrayList<String>();

    for(int i=0;i<numberlist.size();i++) {

        sendMsg(numberlist.get(i));
    }

    return super.onStartCommand(intent, flags, startId);
}

public void sendMsg(final String num){
    String SENT = "SMS_SENT";
    final SmsManager sms = SmsManager.getDefault();
    final PendingIntent sentPI = PendingIntent.getBroadcast(MyService.this, 0,new Intent(SENT), 0);
    Handler h = new Handler();
    h.postDelayed(new Runnable() {
        @Override
        public void run() {
            sms.sendTextMessage(num, null, "Hi MyApp SMS", sentPI, null);
        }
    }, 2000);
}

答案 1 :(得分:0)

尝试发送SMS OnPost方法或在主线程上运行AsynTask。 按照this link帮助