Android 製作群發簡訊並查詢發送狀態(TextWatcher,BroadcastReceiver)

功能簡單
一、可以選取通訊錄名單
二、可以跟據名單群體發送
三、可以查詢發送狀態(是否送出成功)
四、可以監聽文字變化事件

不過有些小地方卡了一下做個紀錄:

TextWatcher:用來監聽EditText裡文字變化事件
BroadcastReceiver:廣播接收元件,用來監聽有沒有Intent呼叫

Intent就像要做件事的意圖
IntentFilter是用來過濾Intent有沒有相符的元件

舉個郵局的比喻
Intent就像信封
IntentFilter就像寫在上面的地址

信封(Intent) 寫好發出時
郵差(Android系統) 會跟據上面的
地址(IntentFilter) 去送信
BroadcastReceiver會跟據信的內容去做它的事

我知道這個比喻不太完美
因為Intent不只對BroadcastReceiver
還可以用在Action、Service
不過先這樣吧~

TextWatcher就簡單多了,有時有些欄位是必填的
可以用這監聽有沒有填寫,或者還可以對應
Regular Expression 正則表示式 (一直覺得這翻譯好帥,正則表示式)
限制字數、規範等等















程式碼:
public static class PlaceholderFragment extends Fragment {
 Button choice,send;
 EditText inputText,etList;
 HashMap name_number;
 
 public PlaceholderFragment() {
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_main, container,
    false);
  choice = (Button) rootView.findViewById(R.id.choice);
  send = (Button) rootView.findViewById(R.id.send);
  inputText = (EditText) rootView.findViewById(R.id.inputText);
  etList = (EditText) rootView.findViewById(R.id.etList);
  //設定IntentFilter過濾器
  IntentFilter iFilter = new IntentFilter("SMS_SEND_ACTION");
  //new出自訂的BroadcastReceiver
  myBroadcastReceiver receiver = new myBroadcastReceiver();
  //將其註冊
  getActivity().registerReceiver(receiver, iFilter);
  //new出清單
  name_number = new HashMap<>();
  //先將發送鈕false
  send.setEnabled(false);
  
  //設定文字變化監聽事件
  inputText.addTextChangedListener(watcher);
  etList.addTextChangedListener(watcher);
  //設定選取連絡人事件
  choice.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    //呼叫連絡人選取名單(單選)
    Uri uri = Uri.parse("content://contacts/people");
    Intent intent = new Intent(Intent.ACTION_PICK,uri);
    startActivityForResult(intent, 1);
    
   }
  });
  
  //設定按下發送事件
  send.setOnClickListener(new OnClickListener() { 
   @Override
   public void onClick(View v) {
    //從Map裡將清單撈出並逐一發送
    Set keys = name_number.keySet();
    Iterator iterator = keys.iterator();
    while(iterator.hasNext()){
     Object key = iterator.next();
     String phone = name_number.get(key);
     sendText(phone,v);
     v.setEnabled(false);
    }
   }
  });
  return rootView;
 }
 
 //---------------------------------------------------------------
 //監聽文字變化事件-----------------------------------------------
 private TextWatcher watcher = new TextWatcher() {
  
  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
   //若文字為空,則不能發送
   if(etList.getText().length() == 0 ||
      inputText.getText().length() == 0){
    send.setEnabled(false);
   }else {
    send.setEnabled(true);
   }
  }
  @Override
  public void beforeTextChanged(CharSequence s, int start, int count,
    int after) {
  }
  @Override
  public void afterTextChanged(Editable s) {
  }
 };
 
 //--------------------------------------------------------------------
 //發送訊息--------------------------------------------------------
 public void sendText(String number,View v){  
  Intent sendIntent = new Intent("SMS_SEND_ACTION");
  PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0,sendIntent , 0);
  SmsManager smsManager = SmsManager.getDefault();
  String text = inputText.getText().toString();
  smsManager.sendTextMessage(number, null, text, pi, null);
  v.setEnabled(true);
 }
 
 //--------------------------------------------------------------------
 //選取聯絡人視窗------------------------------------------------------
 @Override
 public void onActivityResult(int requestCode, int resultCode,
   Intent data) {
  //除了要檢查requestCode是否相符
  //data也要檢查是否為null
  if(requestCode == 1 && data != null){
   Uri myuri = data.getData();
   if(myuri != null){
    try{
     //找出姓名
     Cursor cursor = getActivity().getContentResolver()
       .query(myuri, null, null, null, null);
     cursor.moveToFirst();
     //取得姓名
     String name = cursor.getString(
      cursor.getColumnIndex(Contacts.DISPLAY_NAME));
     //取得ID
     long id = cursor.getLong(
      cursor.getColumnIndex(Contacts._ID));
     //依ID 找出電話
     Cursor cursorNumber = getActivity().getContentResolver()
       .query(Phone.CONTENT_URI, null, 
           Phone.CONTACT_ID + "=" + Long.toString(id), null, null);
     String phonenumber = "";  
     while(cursorNumber.moveToNext()){
      phonenumber = cursorNumber.getString(
        cursorNumber.getColumnIndex(Phone.NUMBER));
     }
     //如果name_number裡有值且對應到姓名
     //表示重複則移除,不然就加進去
     if(phonenumber.equals(name_number.get(name))){
      name_number.remove(name);
     }else{
      name_number.put(name, phonenumber);
     }
      
     String list = reFlashlist(name_number);
     etList.setText(list);
    }catch(Exception e){
     e.printStackTrace();
    }
   }
  
  
  } 
  super.onActivityResult(requestCode, resultCode, data);
 }
 
 //----------------------------------------------------------------
 //重整選擇畫面----------------------------------------------------
 public String reFlashlist(HashMap name_number){
  String tempNamePhone="";
  Set keyName = name_number.keySet(); 
  Iterator iterator = keyName.iterator();
  
  while(iterator.hasNext()){
   Object key = iterator.next();
   String temString = (String) key;
   String temPhone = name_number.get(key);
   tempNamePhone += temString +":" +temPhone+"\n";
  }
  return tempNamePhone;
 }
 
 //--------------------------------------------------------------------
 //設定BroadcastReceiver-----------------------------------------------
 public class myBroadcastReceiver extends BroadcastReceiver{

  @Override
  public void onReceive(Context context, Intent intent) {
   switch (getResultCode()) {
   //getResultCode()取得送出後回傳的代碼
   //依代碼決定顯示什麼提醒
   case Activity.RESULT_OK:
    Toast.makeText(getActivity(), "發送成功"+getResultCode(),Toast.LENGTH_SHORT).show();
    break;
   case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
    Toast.makeText(getActivity(), "發送失敗",Toast.LENGTH_SHORT).show();
    break;
   case SmsManager.RESULT_ERROR_RADIO_OFF:
    Toast.makeText(getActivity(), "飛航模式",Toast.LENGTH_SHORT).show();
    break;
   default:
    Toast.makeText(getActivity(), "未知"+getResultData()
      ,Toast.LENGTH_SHORT).show();
    break;
   }
   
  }
  
 }
}

留言

熱門文章