3

我正在开发一个需要向特定电话号码发送短信的应用程序。我可以使用以下代码发送短信。

try {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, sms, null, null);
                Toast.makeText(getApplicationContext(), "SMS Sent!",
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "SMS faild, please try again later!",
                        Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

现在我想要的是短信应该自动发送。消息应该自动发送的时间存储在 MySQL 数据库中。所以我需要代码在那个时间到来时继续检查,然后自动将消息发送到那个号码。它是一种提醒的东西。用户将在应用程序中保留提醒,例如;我需要在 1 小时后收到一条消息。所以 1 小时后应该会收到消息。PLZ帮忙??

终于我明白了。

/** Code For reminder is here */
            int time=Integer.parseInt(answer);
            int num = (int)System.currentTimeMillis();  
            Intent intent = new Intent(getApplication(), MyBroadcastReceiver.class);
            intent.putExtra("phoneNo",phoneNo);   
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.MINUTE, time);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getApplicationContext(), num, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + calendar.getTimeInMillis() , pendingIntent);
            Toast.makeText(getApplication(), "Alarm set in " + time + " minutes",
            Toast.LENGTH_SHORT).show();
            /** Code for reminder is over */

我的接收者代码是

 public void onReceive(Context context, Intent intent) {
    String sms= "Your turn is about to come. Please be ready. Thank You";
    String phoneNo;
    Bundle extrasBundle = intent.getExtras();
    phoneNo=extrasBundle.getString("phoneNo");
    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, sms, null, null);
        Toast.makeText(context, "SMS Sent to " + phoneNo,Toast.LENGTH_LONG).show();
        } catch (Exception e) {
        Toast.makeText(context,"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
        }

}

以防万一有人需要这个...谢谢

4

2 回答 2

3

为此目的使用AlarmManager 。创建一个接收器,在清单文件中注册它。使用 alarmaManager 在特定时间后设置警报。在接收时将您的 SendSMS 代码放入 Receiver。

编辑:我很早就回答了这个问题,它不适合当前场景,请阅读此博客以获得更好的替代方案后台调度程序

于 2012-07-10T09:12:04.970 回答
2

Alarmmanager 帮助您在特定时间调用,使用 AlarmManager 并将您发送消息的所有代码放在 BroadcastReceiver 的 OnReceive 方法中。按照这个链接。还要记住更改清单文件。祝一切顺利 :)

于 2012-07-10T09:18:05.797 回答