我正在为Android编写此代码,这将允许我在按钮单击(发送)的某个时间发送消息。为此,我创建了一个实现TimerTask的类,以便代码在指定时运行。这适用于从5分钟到1小时的短时间间隔,但是当我将代码设置为在一小时后运行时,它将不会执行。我不确定我是否编码错误或者这是一个常见问题,但我想知道是否有解决方法。
相关守则:
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(isEmpty(message)){
Toast.makeText(getBaseContext(), "please enter a message", Toast.LENGTH_LONG).show();
}
else{
sendMessageAt();
}
}
});
public void sendMessageAt(){
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date;
try {
date = dateFormatter.parse(getDateTime());
Timer timer = new Timer();
TimerTask executeCode = new Execute();
timer.schedule(executeCode,date);
Toast.makeText(getBaseContext(), "Your message will be sent at: "+getDateTime(), Toast.LENGTH_LONG).show();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class Execute extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
String phoneNm="2017257831";
message = (EditText) findViewById(R.id.message);
String mesToStr = message.getText().toString();
sendSMS(phoneNm,mesToStr);
}
}
private void sendSMS(String phoneNm,String message){
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class),0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNm,null,message,pi,null);
}