我正在开发我的第一个应用程序,我的目标是从用户设置的日期和时间开始发送一系列预定义的短信,然后在相对于第一个的设定时间发送(即发送的第一个短信,发送的第二个短信) + 3分钟,第3个短信发送+ 7分钟等)。我设法通过使用不同的pendingintent请求代码一次设置所有警报并为每条消息设置多个广播接收器来实现此目的,但这似乎并不高效。是否可以重复使用相同的请求代码(以取消可能的系列)并在收到每个广播后从同一个接收器设置警报?以下代码,欢迎任何建议。
主要活动
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);
};
}
答案 0 :(得分:0)
将“state”存储在文件,共享首选项或sqlite数据库中。然后你只需要在应用程序唤醒时进行一系列工作,然后你可以选择一个警报和广播接收器。
我在这里有一个简单的SharedPreferences示例:
答案 1 :(得分:0)
下面的代码对我来说很好......
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
for (int count = 1; count <= total_sms; count++) {
Log.i("----------------ppp------------",
"-----working-----------" + count);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number1, null,
"Hai this is to test duration", null, null);
Log.i("SMS_COUNT", "Number of sms send---" +count);
Thread.sleep(1000 * (Integer.parseInt(delay)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
t.start();