模拟器测试中文可能有乱码,这个与模拟器本身编码有关,换到真机就好了。
权限
<uses-permission android:name="android.permission.SEND_SMS" />
import android.app.Activity;
import android.app.PendingIntent;import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
super.onCreate();
sendSMS();
}
public void onDestroy() {
super.onDestroy();
Log.d("keke", "服务销毁");
}
private void sendSMS() {
String phone="5554";
String message="test";
SmsManager sms = SmsManager.getDefault();// 通过SmsManager类的静态方法得到一个类的实例对象
String SENT_SMS_ACTION = "SENT_SMS_ACTION";
String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
// create the sentIntent parameter
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,
0);
// create the deilverIntent parameter
Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0,
deliverIntent, 0);
// register the Broadcast Receivers
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context _context, Intent _intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(),
"SMS sent success actions", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(),
"SMS generic failure actions", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast
.makeText(getBaseContext(),
"SMS radio off failure actions",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(),
"SMS null PDU failure actions", Toast.LENGTH_SHORT)
.show();
break;
}
}
}, new IntentFilter(SENT_SMS_ACTION));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context _context, Intent _intent) {
Toast.makeText(getBaseContext(), "SMS delivered actions",
Toast.LENGTH_SHORT).show();
}
}, new IntentFilter(DELIVERED_SMS_ACTION));
sms.sendTextMessage(phone, null, message, sentPI, deliverPI);// 这是这个类发短信的方法
}
}