android短信发送器源代码

Activity类:

import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class SmsActivity extends Activity {
 private EditText phoneText; 
 private EditText contentText;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        phoneText=(EditText)findViewById(R.id.phoneText);
        contentText=(EditText)findViewById(R.id.contentText);
       
        sendSms();
    }
   
    public void sendSms(){      
        Button button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new SmsOnClick());
    }
   
    private final class SmsOnClick implements OnClickListener{
  @Override
  public void onClick(View v) {
   String phonenumber=phoneText.getText().toString();
   String content=contentText.getText().toString();
   
   if(phonenumber==null||phonenumber.length()<1){
    Toast.makeText(SmsActivity.this, R.string.empty, Toast.LENGTH_SHORT).show();
   }else{
    SmsManager smsManager = SmsManager.getDefault();
    PendingIntent sentIntent = PendingIntent.getBroadcast(SmsActivity.this,0, new Intent(), 0);
    if (content.length() > 70) {// 如果字数超过70,需拆分成多条短信发送
     List<String> msgs = smsManager.divideMessage(content);
     for (String msg : msgs) {
      smsManager.sendTextMessage(phonenumber, null, msg, sentIntent, null);
      // 最后二个参数为短信已发送的广播意图,最后一个参数为短信对方已收到短信的广播意图
     }
    } else {
     smsManager.sendTextMessage(phonenumber, null, content, sentIntent, null);
    }
   }
  }     
    }
}

 

Manifest添加sms permission

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

posted @ 2014-06-12 09:07  xiaochao1234  阅读(572)  评论(0编辑  收藏  举报