SharedPreferences类型中的方法getLong(String,long)不适用于参数(String)

时间:2013-06-20 15:04:12

标签: java android string sharedpreferences long-integer

我收到一条错误消息,指出“在SharedPreferences类型中的方法getLong(String,long)不适用于行上的参数(String)”(一直到我的代码末尾):< / p>

 long oldTime = pref.getLong("smstimestamp");

但是我不确定如何解决这个问题。

有什么建议吗?

来源:

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
                // long days_30 = 1000 * 60 * 60 * 24 * 30;
                SharedPreferences pref = getApplicationContext()
                        .getSharedPreferences("DataCountService", 0);
                // long oldTime = pref.getLong("smstimestamp");
                // 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;
    }

    // }

    @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");
                 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();

4 个答案:

答案 0 :(得分:1)

如果找不到密钥"smstimestamp",则会返回默认值,在本例中为0

long oldTime = pref.getLong("smstimestamp", 0);

答案 1 :(得分:1)

有什么可以解决的? documentation明确指出您需要两个属性:

abstract long getLong(String key, long defValue)

因此,请使用某个默认属性调用getLong()(取决于您在 prefs 中没有值时的预期。可能只是0-1)。

答案 2 :(得分:0)

当您尝试访问共享首选项中的值时,它需要一个默认值(如果未找到该键)。所以改成它:

long oldTime = pref.getLong("smstimestamp", 0);

其中0是您想要的默认值。

  

defValue:如果此首选项不存在则返回的值

答案 3 :(得分:0)

SharedPreferences类有一个方法getLong(String,long),带有两个参数。哟只能用一个参数调用它。

如果没有带“smstimestamp”键的“首选项”,则第二个参数(长)可能是返回的默认值。放置任何值(0或-1)并验证返回值

long oldTime = pref.getLong("smstimestamp"-1);
if (oldTime==-1) {
   // There is no smstimestamp
}