服务以不正确的间隔执行SMS

时间:2013-06-20 15:31:42

标签: java android service time android-alarms

我编写了一个应用程序来检查用户的移动和wifi数据使用情况并发送给VIA短信 - 但是SMS消息每15秒发送一次(服务重复),而不是检查以确保它没有被发送在过去30天内执行。

我已经实现了一些代码,这些代码应该阻止服务发送短信,除非过了30天 - 但它似乎没有工作 - 它每15秒发送一次短信(这是不希望的。)

// check to ensure proper time has elapsed

        long days_30 = 1000 * 60 * 60 * 24 * 30;
        long oldTime = pref.getLong("smstimestamp", 0);
        if (System.currentTimeMillis() - oldTime > days_30) {


// send traffic info via sms & save the current time


    SmsManager smsManager = SmsManager.getDefault();
        smsManager
                .sendTextMessage("7862611848", null, info, null, null);
        String alarm = Context.ALARM_SERVICE;

        SharedPreferences.Editor editor = pref.edit();
        editor.putLong("smstimestamp", System.currentTimeMillis());
        editor.commit();

//完整源代码:

public class DataCountService extends Service {
    String text = "USR;1";
    String ERROR = "DataCountService";
    private Timer timer = new Timer();
    private final long PERIOD = 1000 * 15; // x min
    private final long DELAY_INTERVAL = 0; // x Seconds

    private Intent getIntent() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(Constants.TAG, "Logging Service Started");

        if (intent == null) {
            // Exit gracefully is service not started by intent
            Log.d(Constants.TAG, "Error: Null Intent");
        } else {
            Bundle extras = intent.getExtras();
            text = extras.getString(Constants.DM_SMS_CONTENT);
            // check for Enable or Disable Value - if set to enable
            if (text.contains("//USR;1")) {

                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");
                String tag = ";";
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String info = String.format("USI%sCN%s,WN%s", tag, mobileStr,
                        totalStr);

                // check to ensure proper time has elapsed
                SharedPreferences pref = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                long days_30 = 1000 * 60 * 60 * 24 * 30;
                long oldTime = pref.getLong("smstimestamp", 0);
                if (System.currentTimeMillis() - oldTime > days_30) {

                    // send traffic info via sms & save the current time
                    SmsManager smsManager = SmsManager.getDefault();
                    if (Config.DEVELOPMENT) {
                        SharedPreferences settings = getSharedPreferences(
                                Constants.PREFS_NAME, 0);
                        String shortCode = settings.getString(
                                Constants.PREFS_KEY_SHORT_CODE,
                                Constants.DEFAULT_SHORT_CODE);
                        smsManager.sendTextMessage(shortCode, null, info, null,
                                null);
                        SharedPreferences.Editor editor = pref.edit();
                        editor.putLong("smstimestamp",
                                System.currentTimeMillis());
                        editor.commit();

                    } else {
                        SmsManager ackSMS = SmsManager.getDefault();
                        smsManager.sendTextMessage(
                                Constants.DEFAULT_SHORT_CODE, null, info, null,
                                null);
                    }

                    String alarm = Context.ALARM_SERVICE;

                    // TODO Auto-generated method stub

                    // check for Enable or Disable Value - if set to disable
                } else if

                (text.contains("//USR;0")) {
                    stopSelf();

                    // check for Enable or Disable Value - if set to any other
                    // character
                } else {

                    Log.e(ERROR, "Invalid Enable/Disable Value");

                }
            }
            return START_NOT_STICKY;
        }
        return startId;

    }

    @Override
    public void onCreate() {
        startServiceTimer();
    }

    /*
     * @Override public void onCreate() extends PhoneStateListener {
     * 
     * 
     * EndCallListener callListener = new EndCallListener(); TelephonyManager
     * mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
     * mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE); }
     */

    public void onCallStateChanged(int state, String incomingNumber) {
        if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
            // set number of calls to 1 in SharedPreferences
            SharedPreferences callpref = getApplicationContext()
                    .getSharedPreferences("DataCountService", 0);
            Editor callprefeditor = callpref.edit();
            callprefeditor.putString("calls", "1");
            callprefeditor.commit();

        }

        SharedPreferences pref = getApplicationContext().getSharedPreferences(
                "DataCountService", 0);

        if (pref.getString("calls", "1") == "1") {

            Bundle extras = getIntent().getExtras();
            // check for Enable or Disable Value - if set to enable
            if (text.contains("USI;1;")) {

                // String swappedMdn(Context ctx){
                TelephonyManager tm = (TelephonyManager) getApplicationContext()
                        .getSystemService(Context.TELEPHONY_SERVICE);
                // Extract the phone number from the TelephonyManager instance
                String mdn = tm.getLine1Number();
                // Insure MDN is 10 characters
                if (mdn.length() < 10 || mdn == null)
                    mdn = "0000000000";
                // Extract last 10 digits of MDN
                if (mdn.length() > 10)
                    mdn = mdn.substring(mdn.length() - 10, mdn.length());
                char data[] = mdn.toCharArray();
                char digit;
                for (int index = 0; index < mdn.length() - (mdn.length()) % 2; index += 2) {
                    digit = data[index];
                    data[index] = data[index + 1];
                    data[index + 1] = digit;
                }
                return;
            }

            // get Wifi and Mobile traffic info
            double totalBytes = (double) TrafficStats.getTotalRxBytes()
                    + TrafficStats.getTotalTxBytes();
            double mobileBytes = TrafficStats.getMobileRxBytes()
                    + TrafficStats.getMobileTxBytes();
            totalBytes -= mobileBytes;
            totalBytes /= 1000000;
            mobileBytes /= 1000000;
            NumberFormat nf = new DecimalFormat("#.###");
            String tag = ";";
            String mobileStr = nf.format(mobileBytes);
            String totalStr = nf.format(totalBytes);
            String info = String.format("USI%sCN%s,WN%s", tag, mobileStr,
                    totalStr);

            // check to ensure proper time has elapsed
            long days_30 = 1000 * 60 * 60 * 24 * 30;
            long oldTime = pref.getLong("smstimestamp", 0);
            if (System.currentTimeMillis() - oldTime > days_30) {

                // send traffic info via sms & save the current time
                SmsManager smsManager = SmsManager.getDefault();
                smsManager
                        .sendTextMessage("7865555555", null, info, null, null);
                String alarm = Context.ALARM_SERVICE;

                SharedPreferences.Editor editor = pref.edit();
                editor.putLong("smstimestamp", System.currentTimeMillis());
                editor.commit();
                // TODO Auto-generated method stub

                // check for Enable or Disable Value - if set to disable
            } else if

            (text.contains("USI;1;")) {
                stopSelf();

                // check for Enable or Disable Value - if set to any other
                // character
            } else {

                Log.e(ERROR, "Invalid Enable/Disable Value");

            }

        }

    }

    private void startServiceTimer() {
        timer.schedule(new TimerTask() {
            public void run() {

                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");
                String tag = ";";
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String info = String.format("USI%sCN%s,WN%s", tag, mobileStr,
                        totalStr);

                // save Network and Wifi data in sharedPreferences

                SharedPreferences cnwn = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                Editor editor = cnwn.edit();
                editor.putString("last_month", info);
                editor.commit();

                // check to ensure proper time has elapsed
                SharedPreferences pref = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                long days_30 = 1000 * 60 * 60 * 24 * 30;
                long oldTime = pref.getLong("smstimestamp", 0);
                if (System.currentTimeMillis() - oldTime > days_30) {

                    // send SMS (with Wifi usage and last month's Data usage)
                    // and
                    // save the current time
                    String sms = "";

                    SmsManager smsManager = SmsManager.getDefault();
                    if (Config.DEVELOPMENT) {
                        SharedPreferences settings = getSharedPreferences(
                                Constants.PREFS_NAME, 0);
                        String shortCode = settings.getString(
                                Constants.PREFS_KEY_SHORT_CODE,
                                Constants.DEFAULT_SHORT_CODE);
                        smsManager.sendTextMessage(shortCode, null,
                                sms + cnwn.getString("last_month", ""), null,
                                null);
                        editor.putLong("smstimestamp",
                                System.currentTimeMillis());
                        editor.commit();
                    } else {
                        SmsManager ackSMS = SmsManager.getDefault();
                        smsManager.sendTextMessage(
                                Constants.DEFAULT_SHORT_CODE, null,
                                sms + cnwn.getString("last_month", ""), null,
                                null);
                    }

                }
            }
        }, DELAY_INTERVAL, PERIOD);
    }

    @Override
    public IBinder onBind(Intent intent) {

        // TODO Auto-generated method stub

        return null;

    }

    @Override
    public boolean onUnbind(Intent intent) {

        // TODO Auto-generated method stub

        return super.onUnbind(intent);

    }

}

编辑#1

来源:

public class DataCountService extends Service {
    String text = "USR;1";
    String ERROR = "DataCountService";
    private Timer timer = new Timer();
    private final long PERIOD = 1000 * 15; // x min
    private final long DELAY_INTERVAL = 0; // x Seconds

    private Intent getIntent() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(Constants.TAG, "Logging Service Started");

        if (intent == null) {
            // Exit gracefully is service not started by intent
            Log.d(Constants.TAG, "Error: Null Intent");
        } else {
            Bundle extras = intent.getExtras();
            text = extras.getString(Constants.DM_SMS_CONTENT);
            // check for Enable or Disable Value - if set to enable
            if (text.contains("//USR;1")) {

                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");
                String tag = ";";
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String info = String.format("USI%sCN%s,WN%s", tag, mobileStr,
                        totalStr);

                // check to ensure proper time has elapsed
                SharedPreferences pref = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                 long days_30 = 1000; // * 60 * 60 * 24 * 30;
                 long oldTime = pref.getLong("smstimestamp", 0);
                 if(System.currentTimeMillis() - oldTime > days_30){

                // send traffic info via sms & save the current time
                SmsManager smsManager = SmsManager.getDefault();
                if (Config.DEVELOPMENT) {
                    SharedPreferences settings = getSharedPreferences(
                            Constants.PREFS_NAME, 0);
                    String shortCode = settings.getString(
                            Constants.PREFS_KEY_SHORT_CODE,
                            Constants.DEFAULT_SHORT_CODE);
                    smsManager.sendTextMessage(shortCode, null, info, null,
                            null);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putLong("smstimestamp", System.currentTimeMillis());
                    editor.commit();

                } else {
                    SmsManager ackSMS = SmsManager.getDefault();
                    smsManager.sendTextMessage(Constants.DEFAULT_SHORT_CODE,
                            null, info, null, null);
                }

                String alarm = Context.ALARM_SERVICE;

                // TODO Auto-generated method stub

                // check for Enable or Disable Value - if set to disable
            } else if

            (text.contains("//USR;0")) {
                stopSelf();

                // check for Enable or Disable Value - if set to any other
                // character
            } else {

                Log.e(ERROR, "Invalid Enable/Disable Value");

            }
        }
        return START_NOT_STICKY;
    }
        return startId;

     }

    @Override
    public void onCreate() {
        startServiceTimer();
    }

    /*
     * @Override public void onCreate() extends PhoneStateListener {
     * 
     * 
     * EndCallListener callListener = new EndCallListener(); TelephonyManager
     * mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
     * mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE); }
     */

    public void onCallStateChanged(int state, String incomingNumber) {
        if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
            // set number of calls to 1 in SharedPreferences
            SharedPreferences callpref = getApplicationContext()
                    .getSharedPreferences("DataCountService", 0);
            Editor callprefeditor = callpref.edit();
            callprefeditor.putString("calls", "1");
            callprefeditor.commit();


        }

        SharedPreferences pref = getApplicationContext().getSharedPreferences(
                "DataCountService", 0);

        if (pref.getString("calls", "1") == "1") {

            Bundle extras = getIntent().getExtras();
            // check for Enable or Disable Value - if set to enable
            if (text.contains("USI;1;")) {




        //      String swappedMdn(Context ctx){ 
                    TelephonyManager tm = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
                    //Extract the phone number from the TelephonyManager instance
                    String mdn = tm.getLine1Number();
                    //Insure MDN is 10 characters
                    if (mdn.length() < 10 || mdn == null) mdn ="0000000000";
                    //Extract last 10 digits of MDN
                    if (mdn.length() > 10) mdn = mdn.substring(mdn.length() - 10, mdn.length()); 
                    char data[] = mdn.toCharArray();
                    char digit;
                    for (int index = 0; index < mdn.length() - (mdn.length())%2; index+=2){
                        digit = data[index];
                        data[index] = data[index+1];
                        data[index+1] = digit;
                    }
                    return; 
                }



                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");
                String tag = ";";
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String info = String.format("USI%sCN%s,WN%s", tag, mobileStr,
                        totalStr);

                // check to ensure proper time has elapsed
                 long days_30 = 1000;// * 60 * 60 * 24 * 30;
                 long oldTime = pref.getLong("smstimestamp", 0);
                 if(System.currentTimeMillis() - oldTime > days_30){

                // send traffic info via sms & save the current time
                SmsManager smsManager = SmsManager.getDefault();
                smsManager
                        .sendTextMessage("7862611848", null, info, null, null);
                String alarm = Context.ALARM_SERVICE;

                SharedPreferences.Editor editor = pref.edit();
                editor.putLong("smstimestamp", System.currentTimeMillis());
                editor.commit();
                // TODO Auto-generated method stub

                // check for Enable or Disable Value - if set to disable
            } else if

            (text.contains("USI;1;")) {
                stopSelf();

                // check for Enable or Disable Value - if set to any other
                // character
            } else {

                Log.e(ERROR, "Invalid Enable/Disable Value");

            }

        }

    }


    private void startServiceTimer() {
        timer.schedule(new TimerTask() {
            public void run() {

                // get Wifi and Mobile traffic info
                double totalBytes = (double) TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes();
                double mobileBytes = TrafficStats.getMobileRxBytes()
                        + TrafficStats.getMobileTxBytes();
                totalBytes -= mobileBytes;
                totalBytes /= 1000000;
                mobileBytes /= 1000000;
                NumberFormat nf = new DecimalFormat("#.###");
                String tag = ";";
                String mobileStr = nf.format(mobileBytes);
                String totalStr = nf.format(totalBytes);
                String info = String.format("USI%sCN%s,WN%s", tag, mobileStr,
                        totalStr);

                // save Network and Wifi data in sharedPreferences

                SharedPreferences cnwn = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                Editor editor = cnwn.edit();
                editor.putString("last_month", info);
                editor.commit();

                // check to ensure proper time has elapsed
                SharedPreferences pref = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                 long days_30 = 1000; // * 60 * 60 * 24 * 30;
                 long oldTime = pref.getLong("smstimestamp", 0);
                 if(System.currentTimeMillis() - oldTime > days_30){

                // send SMS (with Wifi usage and last month's Data usage) and
                // save the current time
                String sms = "";

                SmsManager smsManager = SmsManager.getDefault();
                if (Config.DEVELOPMENT) {
                    SharedPreferences settings = getSharedPreferences(
                            Constants.PREFS_NAME, 0);
                    String shortCode = settings.getString(
                            Constants.PREFS_KEY_SHORT_CODE,
                            Constants.DEFAULT_SHORT_CODE);
                    smsManager.sendTextMessage(shortCode, null,
                            sms + cnwn.getString("last_month", ""), null, null);
                        editor.putLong("smstimestamp", System.currentTimeMillis());
                    editor.commit();
                } else {

                    SmsManager ackSMS = SmsManager.getDefault();
                    smsManager.sendTextMessage(Constants.DEFAULT_SHORT_CODE,
                            null, sms + cnwn.getString("last_month", ""), null,
                            null);
                    editor.putLong("smstimestamp", System.currentTimeMillis());
                    editor.commit();
                }

            }
            }}, DELAY_INTERVAL, PERIOD);
        }


    @Override
    public IBinder onBind(Intent intent) {

        // TODO Auto-generated method stub

        return null;

    }

    @Override
    public boolean onUnbind(Intent intent) {

        // TODO Auto-generated method stub

        return super.onUnbind(intent);

    }

}

1 个答案:

答案 0 :(得分:0)

你的timerTask每15秒射击一次......你确定首选项存储并返回正确的值吗?在我看来,你的情况System.currentTimeMillis() - oldTime > days_30永远都是真的。

在timentask中,在非“Config.DEVELOPMENT”分支中发送SMS后,实际上并未设置“oldTime”。

你应该摆脱代码重复并确保实际执行了哪些代码:

  • 使用(私人)方法。
  • 使用记录。

使用更清晰的代码可以节省大量的汗水。