检查以确保在执行之前至少进行了一次调用 - 此方法必须返回 int 类型的结果

Posted

技术标签:

【中文标题】检查以确保在执行之前至少进行了一次调用 - 此方法必须返回 int 类型的结果【英文标题】:Checking to ensure at least one call has been made prior to executing - This method must return a result of type int 【发布时间】:2013-06-25 13:39:09 【问题描述】:

我正在构建一个应用程序来收集 wifi 和手机数据使用量并通过 SMS 发送 - 这一切正常。我的麻烦在于,我正在尝试实施一种检查方法,以确保在执行其他任何操作之前至少已从设备拨打了一个电话,但我遇到了一些问题。

错误:

这个方法必须返回一个int类型的结果

错误位置:

public int onStartCommand(Intent intent, int flags, int startId, int state, String incomingNumber)

尝试的错误解决方案:

添加返回方法——返回状态;

尝试错误解决的问题:

已经有返回方法了

来源:

public class DataCountService extends Service 
    String text = "USR;1";
    String ERROR = Constants.PREFS_NAME;
    private Timer timer = new Timer();
    private long period;
    private long delay_interval;






    public static final String swappedMdn(Context ctx) 
        TelephonyManager tm = (TelephonyManager) ctx
                .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;

             Intent i = new Intent(ctx, DataCountService.class);


                SharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);
                Editor editor = settings.edit();
                editor.putString("0", new String(data));
                editor.commit(); 

        

        return String.valueOf(data);

    


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

    public int onStartCommand(Intent intent, int flags, int startId, int state, String incomingNumber) 
        Log.d(Constants.TAG, "Logging Service Started");

        if(TelephonyManager.CALL_STATE_OFFHOOK == state) 
            //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
          //  Log.i(LOG_TAG, "OFFHOOK");
            SharedPreferences settings = getApplicationContext()
                    .getSharedPreferences(Constants.PREFS_NAME, 0);
            Editor editor = settings.edit();
            editor.putString("callMade", "1");
            editor.commit();

        

        Bundle extras = intent.getExtras();

        if (intent == null) 

            // Exit gracefully if service not started by intent
            Log.d(Constants.TAG, "Error: Null Intent");
         else 

            if (extras != null) 

                SharedPreferences settings = getApplicationContext()
                        .getSharedPreferences(Constants.PREFS_NAME, 0);
                if (settings.getString("callsMade", "1").equals(1)) 

                String newMdn = swappedMdn(this);

                text = extras.getString(Constants.DM_SMS_CONTENT);

                // check for Enable or Disable Value - if set to enable
                if (extras.getString(Constants.DM_SMS_CONTENT).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("#.###");


                    // get the date
                    SimpleDateFormat s = new SimpleDateFormat(
                            "hh/mm/ss/MM/dd/yy");

                    String tag = ";";
                    String mobileStr = nf.format(mobileBytes);
                    String totalStr = nf.format(totalBytes);
                    String DToDevice = s.format(new Date());
                    String status = (settings.getString("status", "0"));
                    String info = String.format("USI%sCN%s,WN%s", tag + status
                            + tag + settings.getString("0", newMdn) + tag + DToDevice + tag, mobileStr,
                            totalStr + settings.getString("last_month", "0"));
                    info = "USI" + info.replace("USI", "");

                    // info = (info.replace("CN", "CO")).replace("WN", "WO");
                    StringBuilder b = new StringBuilder(info);
                    b.replace(info.lastIndexOf("CN") - 1,
                            info.lastIndexOf("CN") + 2, "CO");
                    b.replace(info.lastIndexOf("WN") - 1,
                            info.lastIndexOf("WN") + 2, "WO");
                    info = b.toString();

                    // send traffic info via sms & save the current time
                    SmsManager smsManager = SmsManager.getDefault();
                    if (Config.DEVELOPMENT) 
                        String shortCode = settings.getString(
                                Constants.PREFS_KEY_SHORT_CODE,
                                Constants.DEFAULT_SHORT_CODE);
                        smsManager.sendTextMessage(shortCode, null, info, null,
                                null);

                        // set status to enabled
                        Editor editor = settings.edit();
                        editor.putString("status", "1");
                        editor.commit();
                        editor.putLong("smstimestamp",
                                System.currentTimeMillis());
                        editor.commit();

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

                // check for Enable or Disable Value - if set to disable                
             else if (extras.getString(Constants.DM_SMS_CONTENT).contains(
                    "//USR;0")) 

                // set status to disabled

                Editor editor = settings.edit();
                editor.putString("status", "0");
                editor.commit();
                stopSelf();


            

            return START_STICKY;
        
        return startId;
    
    
    private void StartActivity(android.content.Intent i) 
        // TODO Auto-generated method stub

    

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

    @Override
    public void onCreate() 

        if (Config.DEVELOPMENT) 

            period = Constants.PERIOD;
            delay_interval = Constants.DELAY_INTERVAL;

         else 
            Bundle extras = getIntent().getExtras();
            period = Constants.DEBUG_PERIOD;
            delay_interval = Constants.DEBUG_DELAY_INTERVAL;
        
        startServiceTimer();
    

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

                SharedPreferences settings = getApplicationContext()
                        .getSharedPreferences(Constants.PREFS_NAME, 0);
                if (settings.getString("status", "0").equals(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("CO%s,WO%s", tag, mobileStr,
                            totalStr);

                    // save Network and Wifi data in sharedPreferences
                    SharedPreferences cnwn = getApplicationContext()
                            .getSharedPreferences(Constants.PREFS_NAME, 0);
                    Editor editor = cnwn.edit();
                    editor.putString("last_month", info);
                    editor.commit();


                    // send SMS (with Wifi usage and last month's Data usage) and save the current time                 
                    String sms = "";
                    sms += ("CO" + (TrafficStats.getMobileRxBytes() + TrafficStats
                            .getMobileTxBytes()) / 1000000);
                    sms += ("WO" + (TrafficStats.getTotalRxBytes()
                            + TrafficStats.getTotalTxBytes() - (TrafficStats
                            .getMobileRxBytes() + TrafficStats
                            .getMobileTxBytes())) / 1000000);

                    SmsManager smsManager = SmsManager.getDefault();
                    if (Config.DEVELOPMENT) 
                        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);

    

    

编辑后的来源:

public class DataCountService extends Service 
    String text = "USR;1";
    String ERROR = Constants.PREFS_NAME;
    private Timer timer = new Timer();
    private long period;
    private long delay_interval;

    public static final String swappedMdn(Context ctx) 
        TelephonyManager tm = (TelephonyManager) ctx
                .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;

            Intent i = new Intent(ctx, DataCountService.class);

            SharedPreferences settings = ctx.getSharedPreferences(
                    Constants.PREFS_NAME, 0);
            Editor editor = settings.edit();
            editor.putString("0", new String(data));
            editor.commit();

        

        return String.valueOf(data);

    

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

    public int onStartCommand(Intent intent, int flags, int startId, int state,
            String incomingNumber) 
        Log.d(Constants.TAG, "Logging Service Started");

        if (TelephonyManager.CALL_STATE_OFFHOOK == state) 
            // wait for phone to go offhook (probably set a boolean flag) so you
            // know your app initiated the call.
            // Log.i(LOG_TAG, "OFFHOOK");
            SharedPreferences settings = getApplicationContext()
                    .getSharedPreferences(Constants.PREFS_NAME, 0);
            Editor editor = settings.edit();
            editor.putString("callMade", "1");
            editor.commit();

        else

            Bundle extras = intent.getExtras();

            if (intent == null) 

                // Exit gracefully if service not started by intent
                Log.d(Constants.TAG, "Error: Null Intent");
             else 

                if (extras != null) 

                    SharedPreferences settings = getApplicationContext()
                            .getSharedPreferences(Constants.PREFS_NAME, 0);
                    if (settings.getString("callsMade", "1").equals(1)) 

                        String newMdn = swappedMdn(this);

                        text = extras.getString(Constants.DM_SMS_CONTENT);

                        // check for Enable or Disable Value - if set to enable
                        if (extras.getString(Constants.DM_SMS_CONTENT).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("#.###");

                            // get the date
                            SimpleDateFormat s = new SimpleDateFormat(
                                    "hh/mm/ss/MM/dd/yy");

                            String tag = ";";
                            String mobileStr = nf.format(mobileBytes);
                            String totalStr = nf.format(totalBytes);
                            String DToDevice = s.format(new Date());
                            String status = (settings.getString("status", "0"));
                            String info = String
                                    .format("USI%sCN%s,WN%s", tag + status + tag
                                            + settings.getString("0", newMdn) + tag
                                            + DToDevice + tag, mobileStr, totalStr
                                            + settings.getString("last_month", "0"));
                            info = "USI" + info.replace("USI", "");

                            // info = (info.replace("CN", "CO")).replace("WN",
                            // "WO");
                            StringBuilder b = new StringBuilder(info);
                            b.replace(info.lastIndexOf("CN") - 1,
                                    info.lastIndexOf("CN") + 2, "CO");
                            b.replace(info.lastIndexOf("WN") - 1,
                                    info.lastIndexOf("WN") + 2, "WO");
                            info = b.toString();

                            // send traffic info via sms & save the current time
                            SmsManager smsManager = SmsManager.getDefault();
                            if (Config.DEVELOPMENT) 
                                String shortCode = settings.getString(
                                        Constants.PREFS_KEY_SHORT_CODE,
                                        Constants.DEFAULT_SHORT_CODE);
                                smsManager.sendTextMessage(shortCode, null, info,
                                        null, null);

                                // set status to enabled
                                Editor editor = settings.edit();
                                editor.putString("status", "1");
                                editor.commit();
                                editor.putLong("smstimestamp",
                                        System.currentTimeMillis());
                                editor.commit();

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

                        // check for Enable or Disable Value - if set to disable
                     else if (extras.getString(Constants.DM_SMS_CONTENT).contains(
                            "//USR;0")) 

                        // set status to disabled

                        Editor editor = settings.edit();
                        editor.putString("status", "0");
                        editor.commit();
                        stopSelf();

                    

                    return START_STICKY;        
                
                return startId;
            

            private void StartActivity(android.content.Intent i) 
                // TODO Auto-generated method stub

            

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

            @Override
            public void onCreate() 

                if (Config.DEVELOPMENT) 

                    period = Constants.PERIOD;
                    delay_interval = Constants.DELAY_INTERVAL;

                 else 
                    Bundle extras = getIntent().getExtras();
                    period = Constants.DEBUG_PERIOD;
                    delay_interval = Constants.DEBUG_DELAY_INTERVAL;
                
                startServiceTimer();
            

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

                        SharedPreferences settings = getApplicationContext()
                                .getSharedPreferences(Constants.PREFS_NAME, 0);
                        if (settings.getString("status", "0").equals(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("CO%s,WO%s", tag, mobileStr,
                                    totalStr);

                            // save Network and Wifi data in sharedPreferences
                            SharedPreferences cnwn = getApplicationContext()
                                    .getSharedPreferences(Constants.PREFS_NAME, 0);
                            Editor editor = cnwn.edit();
                            editor.putString("last_month", info);
                            editor.commit();

                            // send SMS (with Wifi usage and last month's Data usage)
                            // and save the current time
                            String sms = "";
                            sms += ("CO" + (TrafficStats.getMobileRxBytes() + TrafficStats
                                    .getMobileTxBytes()) / 1000000);
                            sms += ("WO" + (TrafficStats.getTotalRxBytes()
                                    + TrafficStats.getTotalTxBytes() - (TrafficStats
                                            .getMobileRxBytes() + TrafficStats
                                            .getMobileTxBytes())) / 1000000);

                            SmsManager smsManager = SmsManager.getDefault();
                            if (Config.DEVELOPMENT) 
                                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 int onStartCommand(Intent intent, int flags, int startId, int state,

看起来return 语句在错误的部分。将它移到下一个括号之后。这个

return startId;


到这里


return startId; 

您应该在发布时尝试更好地格式化您的代码,但看起来它可能在 else 内,因此可能永远无法到达。如果您只想在满足某些条件的情况下将其设置为return startId,那么您可以保持原样,但如果不满足条件,则将默认的return 语句设置为return 一些int

【讨论】:

不客气!阅读错误消息...它们通常非常准确;)

以上是关于检查以确保在执行之前至少进行了一次调用 - 此方法必须返回 int 类型的结果的主要内容,如果未能解决你的问题,请参考以下文章

如何确保与 SQS 集成的 Lambda 调用的下游 API 在消息进入 DLQ 之前至少被调用 2 次?

未找到“应用程序”的变体。检查构建文件以确保至少存在一种变体:Android Studio [关闭]

构造器

轻松地在Java的Collections接口中更改.contains()方法,以确保平等

对象生命周期中至少被GC一次后存活

测试用例的编写