在Android中定期发送短信

时间:2011-12-27 11:36:21

标签: android sms

我必须通过我的Android应用程序定期发送短信给某些人(朋友)。要发送的消息将仅存储在应用程序的数据库中。

我见过以下主题:

How to send sms programmatically?

Show compose SMS view in Android

1 个答案:

答案 0 :(得分:2)

使用服务:

import java.util.Timer;
import java.util.TimerTask;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class SrvSMSSender extends Service {    

    Timer timerSendSMS = new Timer();

    class taskSendSMS extends TimerTask {
        @Override
        public void run() {
            hSendSMS.sendEmptyMessage(0);
        }
    };

    final Handler hSendSMS = new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            procSendSMS();
            return false;
        }
    });

    public void procSendSMS() {
        try {
            // send your SMS here

        } catch (Exception e) {

        }
    }


    @Override
    public void onCreate() {
        super.onCreate();

    };

    @Override
    public void onStart(Intent intent, int startId) {
        try {
            long intervalSendSMS = 10*60*1000;

            timerSendSMS = new Timer();

            timerSendSMS.schedule(new taskSendSMS(), 0, intervalSendSMS);

        } catch (NumberFormatException e) {
            Toast.makeText(this, "error running service: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "error running service: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {

        timerSendSMS.cancel();
        timerSendSMS.purge();

    }
}