android群发短信到通讯录所有联系人上并动态替换其中联系人信息


    当我们要群发短信,而且需要替换里面的一些信息的时候(比如发送祝福短信,需要在短信里面加入对方姓名时),

做一个简单的群发短信的功能,并用通讯录里面的联系人姓名替换短信里面的#name#字符串,然后发送短信


代码如下:

   main.java

    

package org.androidMarket.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

    /** Called when the activity is first created. */

    private EditText            txtNo;
    private EditText            txtContent;
    private Button              btnSend;
    private Button              btnCancel;

    private final static String PLACEHOLDER_NAME = "#name#";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

//        txtNo = (EditText) findViewById(R.id.txNo);
        txtContent = (EditText) findViewById(R.id.txContent);
        btnSend = (Button) findViewById(R.id.btnSend);
//        btnCancel = (Button) findViewById(R.id.btnCancel);
        
        Display d = getWindowManager().getDefaultDisplay();
        txtContent.setHeight((int) (d.getHeight() * 0.5));

        btnSend.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                String strNo = txtNo.getText().toString();
                String strContent = txtContent.getText().toString();
                SmsManager smsManager = SmsManager.getDefault();
                PendingIntent sentIntent = PendingIntent.getBroadcast(Main.this, 0, new Intent(), 0);
                
                // 如果字数超过70,需拆分成多条短信发送
//                if (strContent.length() > 70) {
//                    List<String> msgs = smsManager.divideMessage(strContent);
//                    for (String msg : msgs) {
//                        smsManager.sendTextMessage(strNo, null, msg, sentIntent, null);
//                    }
//                } else {
//                    smsManager.sendTextMessage(strNo, null, strContent, sentIntent, null);
//                }
                List<Map<String,Object>> contacts = getContact();
                for(Map<String,Object> map : contacts){
                    strContent = strContent.replaceAll(PLACEHOLDER_NAME, getNumberName((String)map.get("textViewMobileNo")));   
                    if (strContent.length() > 70) {
                        List<String> msgs = smsManager.divideMessage(strContent);
                        for (String msg : msgs) {
                            smsManager.sendTextMessage((String)map.get("textViewMobileNo"), null, msg, sentIntent, null);
                        }
                    } else {
                        smsManager.sendTextMessage((String)map.get("textViewMobileNo"), null, strContent, sentIntent, null);
                    }   
                }
                Toast.makeText(Main.this, "短信发送完成", Toast.LENGTH_LONG).show();
            }
        });
        
//        btnCancel.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                txtNo.setText(null);
//                txtContent.setText(null);
//            }
//        });

        // TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // StringBuilder sb = new StringBuilder();
        // sb.append("\nDeviceId(IMEI) = " + tm.getDeviceId());
        // sb.append("\nDeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion());
        // sb.append("\nLine1Number = " + tm.getLine1Number());
        // sb.append("\nNetworkCountryIso = " + tm.getNetworkCountryIso());
        // sb.append("\nNetworkOperator = " + tm.getNetworkOperator());
        // sb.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());
        // sb.append("\nNetworkType = " + tm.getNetworkType());
        // sb.append("\nPhoneType = " + tm.getPhoneType());
        // sb.append("\nSimCountryIso = " + tm.getSimCountryIso());
        // sb.append("\nSimOperator = " + tm.getSimOperator());
        // sb.append("\nSimOperatorName = " + tm.getSimOperatorName());
        // sb.append("\nSimSerialNumber = " + tm.getSimSerialNumber());
        // sb.append("\nSimState = " + tm.getSimState());
        // sb.append("\nSubscriberId(IMSI) = " + tm.getSubscriberId());
        // sb.append("\nVoiceMailNumber = " + tm.getVoiceMailNumber());
        // Log.e("info", sb.toString());

    }

    public List<Map<String, Object>> getContact() {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        // 获得所有的联系人
        Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        // 循环遍历
        if (cur.moveToFirst()) {
            int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);

            int displayNameColumn = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            do {

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("choose", false);
                // 获得联系人的ID号
                String contactId = cur.getString(idColumn);
                // 获得联系人姓名
                String disPlayName = cur.getString(displayNameColumn);

                map.put("textViewName", disPlayName);
                System.out.println("联系人姓名:" + disPlayName);

                // 查看该联系人有多少个电话号码。如果没有这返回值为0
                String phoneNumber = "";
                int phoneCount = cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if (phoneCount > 0) {
                    // 获得联系人的电话号码
                    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                                               null,
                                                               ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                                       + " = " + contactId, null, null);
                    if (phones.moveToFirst()) {
                        do {
                            // 遍历所有的电话号码
                            phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            System.out.println("联系人电话:" + phoneNumber);
                        } while (phones.moveToNext());

                        map.put("textViewMobileNo", phoneNumber);
                    }
                }

                list.add(map);
            } while (cur.moveToNext());

        }
        return list;
    }
    
    public String getNumberName(String phoneNumber){
        // 获得联系人的电话号码
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                                   null,
                                                   ContactsContract.CommonDataKinds.Phone.NUMBER
                                                           + " = " + phoneNumber, null, null);
        if (phones.moveToFirst()) {
            do {
                // 遍历所有的电话号码
                String displayName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                System.out.println("联系人电话:" + phoneNumber);
                System.out.println("联系人名称:" + displayName);
                return displayName;
            } while (phones.moveToNext());
        }
        
        return null;
    }
}


layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<!-- <EditText android:text="" android:layout_height="wrap_content" android:id="@+id/txNo" 
		android:layout_width="match_parent"></EditText> -->
	<EditText android:text="" android:id="@+id/txContent"
		android:layout_width="match_parent" android:layout_alignParentLeft="true"
		android:layout_height="wrap_content" ></EditText>
	<Button android:layout_height="wrap_content" android:text="@string/send"
		android:layout_width="wrap_content" android:id="@+id/btnSend"></Button>
	<!-- <Button android:layout_height="wrap_content" android:text="@string/cancel" 
		android:layout_width="wrap_content" android:id="@+id/btnCancel" android:layout_alignParentBottom="true"></Button> -->
</LinearLayout>


values/string.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SmartSMS</string>
    <string name="cancel">清空</string>
    <string name="send">群发</string>
</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="org.androidMarket.app" android:versionCode="1"
	android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".Main" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
	<uses-permission android:name="android.permission.SEND_SMS" /><!--添加权限 -->
	<uses-permission android:name="android.permission.READ_CONTACTS" /><!--添加权限 -->
</manifest>


已经在手机上实验成功了。



posted @ 2011-07-18 16:04  MXi4oyu  阅读(369)  评论(0编辑  收藏  举报