我正在處理我的第一個應用程序,我的目標是發送一系列預定義的短信,從用戶設置的日期和時間開始,然後相對於第一個設置的時間即發送第一個短信,在+ 3min發送第二個短信,在+ 7min發送第三個短信等)。我設法通過使用不同的待定內容請求代碼一次設置所有的警報,併爲每條消息設置多個廣播接收器,但這看起來效率不高。是否有可能重複使用相同的請求代碼(以取消一系列可能的事件),並在收到每個廣播後從相同的接收器設置一個鬧鐘?下面的代碼,歡迎任何建議。以設定的時間間隔發送一系列預定義的短信
主要活動
Intent intent = new Intent(MainActivity.this,
Receiver1.class);
intent.putExtra(EXTRA_MESSAGE1, message1);
intent.putExtra(EXTRA_NUMBER, number);
Intent intent2 = new Intent(MainActivity.this,
Receiver2.class);
intent2.putExtra(EXTRA_MESSAGE2, message2);
intent2.putExtra(EXTRA_NUMBER, number);
PendingIntent sender = PendingIntent.getBroadcast(
MainActivity.this, 1, intent, 0);
PendingIntent sender2 = PendingIntent.getBroadcast(
MainActivity.this, 2, intent2, 0);
// Set alarm for this time
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, mYear);
cal.set(Calendar.MONTH, mMonth);
cal.set(Calendar.DAY_OF_MONTH, mDay);
cal.set(Calendar.HOUR_OF_DAY, mHour);
cal.set(Calendar.MINUTE, mMinute);
// Schedule alarm
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
AlarmManager am2 = (AlarmManager) getSystemService(ALARM_SERVICE);
am2.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis() + 30 * 1000, sender2);
接收機1個
public class Receiver1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE1);
String number = intent.getStringExtra(MainActivity.EXTRA_NUMBER);
sendSMS(number, message);
};
// ---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
};
}
接收機2
public class Receiver2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE2);
String number = intent.getStringExtra(MainActivity.EXTRA_NUMBER);
sendSMS(number, message);
};
// ---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
};
}
別忘了幫兄弟出來有標記和/或upvote。 – 2013-02-28 14:36:08