したがってSMS
、アプリケーションの機能はほぼ完了しています。最後に行う必要があるToast
のは、メッセージの送信先の番号を表示することです。次のコードがあります。
グローバル変数:
private BroadcastReceiver sendBroadcastReceiver;
private BroadcastReceiver deliveryBroadcastReceiver;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
void onCreate(Bundle savedInstanceState) で宣言:
sendBroadcastReceiver = new BroadcastReceiver()
{
public void onReceive(Context arg0, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
break;
}
}
};
deliveryBroadcastReceiver = new BroadcastReceiver()
{
public void onReceive(Context arg0, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));
registerReceiver(sendBroadcastReceiver , new IntentFilter(SENT));
SMS 送信機能:
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
連絡先(設定に保存されている)をメソッド呼び出しに呼び出す:
ArrayList<String> contacts = new ArrayList();
List<String> list = SM.getAllValue();
for(String string : list){
contacts.add(string);
}
for(int i = 0; i < contacts.size(); i++){
String numberToSend = contacts.get(i).toString();
sendSMS(numberToSend, sms);
}
Whereは、ユーザーの連絡先の をSM.getAllValue()
返します。list
最後に onStop()
@Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(sendBroadcastReceiver);
unregisterReceiver(deliveryBroadcastReceiver);
super.onStop();
}
複数の番号にメッセージを送信すると、次のコードで何度もSMS Sent
乾杯します。SMS Sent to Number1
などのトースト内の数字を指定しSMS sent to Number2
たり、まとめてAll the SMS's were delivered
. 助けてください :)