如何在android中向多人发送短信

时间:2014-03-07 04:43:22

标签: android sms

我正在构建一个应用程序,一次向多个人发送短信。但每当我尝试发送短信时,它会在点击发送按钮后立即关闭并且应用程序停止工作并且不发送消息。如何在关闭后运行它。

package com.example.sms3;

import java.util.ArrayList;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {

    ArrayList<String> name1 = new ArrayList<String>();
    ArrayList<String> phno1 = new ArrayList<String>();
    ArrayList<String> phno0 = new ArrayList<String>();
    MyAdapter ma;
    Button send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.get);
        getAllCallLogs(this.getContentResolver());
        ListView lv = (ListView) findViewById(R.id.lv);
        ma = new MyAdapter();
        lv.setAdapter(ma);
        lv.setOnItemClickListener(this);
        lv.setItemsCanFocus(false);
        lv.setTextFilterEnabled(true);
        send = (Button) findViewById(R.id.button1);
        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                StringBuilder checkedcontacts = new StringBuilder();
                System.out.println(".............." + ma.mCheckStates.size());
                for (int i = 0; i < name1.size(); i++)

                {
                    if (ma.mCheckStates.get(i) == true) {
                        phno0.add(phno1.get(i).toString());
                        checkedcontacts.append(name1.get(i).toString());
                        checkedcontacts.append("\n");

                    } else {
                        System.out.println("..Not Checked......"
                                + name1.get(i).toString());
                    }

                }
                Toast.makeText(MainActivity.this, checkedcontacts, 1000).show();
                Intent returnIntent = new Intent();
                returnIntent.putStringArrayListExtra("name", phno0);
                setResult(RESULT_OK, returnIntent);
                finish();

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        ma.toggle(arg2);
    }

    public void getAllCallLogs(ContentResolver cr) {

        Cursor phones = cr.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, null);
        while (phones.moveToNext()) {
            String name = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            System.out.println(".................." + phoneNumber);
            name1.add(name);
            phno1.add(phoneNumber);
        }

        phones.close();
    }

    class MyAdapter extends BaseAdapter implements
            CompoundButton.OnCheckedChangeListener {
        private SparseBooleanArray mCheckStates;
        LayoutInflater mInflater;
        TextView tv1, tv;
        CheckBox cb;

        MyAdapter() {
            mCheckStates = new SparseBooleanArray(name1.size());
            mInflater = (LayoutInflater) MainActivity.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name1.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub

            return 0;
        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi = convertView;
            if (convertView == null)
                vi = mInflater.inflate(R.layout.row, null);
            tv = (TextView) vi.findViewById(R.id.textView1);
            tv1 = (TextView) vi.findViewById(R.id.textView2);
            cb = (CheckBox) vi.findViewById(R.id.checkBox1);
            tv.setText("Name :" + name1.get(position));
            tv1.setText("Phone No :" + phno1.get(position));
            cb.setTag(position);
            cb.setChecked(mCheckStates.get(position, false));
            cb.setOnCheckedChangeListener(this);

            return vi;
        }

        public boolean isChecked(int position) {
            return mCheckStates.get(position, false);
        }

        public void setChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
        }

        public void toggle(int position) {
            setChecked(position, !isChecked(position));
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            // TODO Auto-generated method stub
            mCheckStates.put((Integer) buttonView.getTag(), isChecked);
        }

    }
}

SmsMultiple.java

package com.example.sms3;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SmsMultiple extends Activity implements OnClickListener {
    BroadcastReceiver smsSentReciver, smsSentDelivery;
    EditText ed1, ed2;
    static int ResultCode = 12;
    ArrayList<String> sendlist = new ArrayList<String>();
    Button b1, b2;
    String contacts = "";
    String delim = ";";
    TextView ed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smssend);
        b2 = (Button) findViewById(R.id.button2);
        ed1 = (EditText) findViewById(R.id.editText1);
        ed2 = (EditText) findViewById(R.id.editText2);
        ed = (TextView) findViewById(R.id.textView1);
        b1 = (Button) findViewById(R.id.button1);
        b2.setOnClickListener(this);
        b1.setOnClickListener(this);
        ed1.setText(null);
        ed2.setText(null);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(smsSentReciver);
        unregisterReceiver(smsSentDelivery);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        smsSentReciver = 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 Fail",
                            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;

                }
            }

        };
        smsSentDelivery = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // 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(smsSentReciver, new IntentFilter("SMS_SENT"));
        registerReceiver(smsSentDelivery, new IntentFilter("SMS_DELIVERED"));

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {

        case R.id.button2:
            Intent a = new Intent(SmsMultiple.this, MainActivity.class);
            startActivityForResult(a, ResultCode);
            break;
        case R.id.button1:

            Log.i("SMS", "Sendlist Size: " + sendlist.size());

            SmsManager smsManager = SmsManager.getDefault();

            String msg = ed2.getText().toString();
            PendingIntent piSend = PendingIntent.getBroadcast(this, 0,
                    new Intent("SMS_SENT"), 0);
            PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0,
                    new Intent("SMS_DELIVERED"), 0);

            Log.i("SMS", "contacts: " + contacts);

            String[] cellArray;
            ed1.append("");
            contacts = ed1.getText().toString();
            cellArray = contacts.toString().split(";");
ed.setText(contacts);
            for (int a1 = 0; a1 < cellArray.length; a1++) {
                smsManager.sendTextMessage(cellArray[a1].toString(), null, msg,
                        piSend, piDelivered);
            }
            ed1.setText(null);
            ed2.setText(null);

            break;
        }

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String str= ed1.getText().toString();

        if (requestCode == ResultCode) {

            if (resultCode == RESULT_OK) {
                sendlist = data.getStringArrayListExtra("name");
                if (sendlist != null) {
                    ed1.setText(null);
                    for (int i = 0; i < sendlist.size(); i++) {
                            ed1.append("<" + sendlist.get(i).toString()+ ">");
                            ed1.append(delim);
                        }

                        ed1.append(str);

                    }

                }

                if (resultCode == RESULT_CANCELED) {

                }

            }
        }

    }

1 个答案:

答案 0 :(得分:0)

要执行后台操作,您可以使用Service类或AsyncTask类。

但你的主要问题如下,

您正在发送以下for循环中的短信,

for (int a1 = 0; a1 < cellArray.length; a1++) 
{
    smsManager.sendTextMessage(cellArray[a1].toString(), null, msg,
    piSend, piDelivered);
}

虽然以编程方式正确地使用了代码,但是当您发送短信时,发送一条短信需要大约300-500毫秒。

这里你的for循环会立即运行并产生问题。所以我建议你在循环中延迟至少500毫秒。这将在发送下一条SMS之前为您的应用程序提供暂停时间。您的应用程序将阅读以发送下一条短信。