Android 簡訊-發送(PendingIntent,SmsManager)

這功能相當簡單
只是2個元件比較難懂
一個是PendingIntent
另一個是SmsManager

我在實作時的參考,就不多說明







注意事項:

  1. 要虛擬2個機器必預設定2個檔,不能同個檔開2次
  2. 記得要開uses permission :SEND_SMS
  3. SmsManager用Eclipse預設會載入import android.telephony.gsm.SmsManager
    不過.gsm.SmsManager已經deprecated了,把gsm去掉就好
元件搞懂了,程式其實容易撰寫
程式碼如下:
public static class PlaceholderFragment extends Fragment {
Button btn;
EditText etTel,etSms;
 public PlaceholderFragment() {
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_main, container,
    false);
  btn = (Button) rootView.findViewById(R.id.button1);
  etTel = (EditText) rootView.findViewById(R.id.editText1);
  etSms = (EditText) rootView.findViewById(R.id.editText2);
  
  btn.setOnClickListener(new OnClickListener() {   
   @Override
   public void onClick(View v) {
    String telStr=  etTel.getText().toString();
    String smsStr = etSms.getText().toString();
    if(PhoneNumberUtils.isGlobalPhoneNumber(telStr)){
     //檢查規格
     v.setEnabled(false);
     //將傳送鈕隱藏到確定傳送完成
     sendSMS(telStr, smsStr, v);
     //呼叫自訂對應的方法
    }else{
     Toast.makeText(getActivity(),"電話號碼不符格式", Toast.LENGTH_SHORT).show();
    }
   }
  }); 
  return rootView;  
 }
 
 private void sendSMS(String telNo,String smsStr,View v){
  Intent intent = new Intent(getActivity(),MainActivity.PlaceholderFragment.class);
  //後來才發現,原來intent其實可以new Intent()就好…不用那麼麻煩

  PendingIntent pi = PendingIntent.getActivity(
       getActivity(),0,intent, 0);
  //將intent包裏
  SmsManager sms = SmsManager.getDefault();
  sms.sendTextMessage(telNo, null, smsStr,pi , null);
  //依pi包裏送出簡訊
  Toast.makeText(getActivity(), "簡訊已送出", Toast.LENGTH_SHORT).show();
  //簡訊發送成功提示
  v.setEnabled(true);
  //將按鈕復原
 }
}

留言

熱門文章