在服务中将String转换为int

时间:2016-11-05 06:46:34

标签: java android android-studio

我正在尝试将String转换为integerInteger.parseInt()曾经工作过,但现在却失败了。它失败了int INTERVAL= (60000 * Integer.parseInt(preferenceTime));我正在尝试动态指定计划定时器的时间 谢谢

public class Service extends Service {

    public SharedPreferences settings;


    private Handler HandleIt = new Handler();
    private Timer timer = new Timer();
    boolean timeout = false;
    //private PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);





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

    //////////////////////////////////////////////

    class TimeDisplayTimerTask extends TimerTask {



        @Override
        public void run() {
            HandleIt.post(new Runnable(){
               public void run(){

                   //SharedPreferences
                   settings = getSharedPreferences("timer_preference", MODE_PRIVATE);
                   String preferenceTime = settings.getString("timer_preference", "");

                  // int INTERVAL=  (60000 * Integer.parseInt(preferenceTime));


                   Toast.makeText(getApplicationContext(), TextonScreen(), Toast.LENGTH_SHORT).show();

                   //get screen light up
                   PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
                   boolean isScreenOn = pm.isScreenOn();
                   if(isScreenOn==false) {
                       pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |  PowerManager.ON_AFTER_RELEASE, "My Tag");
                   }
                   // make a new intent and start it with flag   and send an sms
                   Intent launch = new Intent(getBaseContext(), SMS.class);
                   launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(launch);
               }
            });
        }


    }

    private String TextonScreen()
    {
        timeout = true;
        return "it is running";


    }
    boolean isTimeout()
    {
        return timeout;
    }
    @Override
    public void onCreate() {

        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "Service is created", Toast.LENGTH_SHORT).show();



    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        SharedPreferences settings = getSharedPreferences( getPackageName() + "timer_preference", MODE_PRIVATE);
        String preferenceTime = settings.getString("timer_preference", "");
        int INTERVAL=  (60000 * Integer.parseInt(preferenceTime));



        // TODO Auto-generated method stub
        // Display the Toast Message
        Toast.makeText(this, "Start Service", Toast.LENGTH_SHORT).show();
        // Execute an action after period time
        //comes from the TimeDisplayTimerTask class
        timer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, INTERVAL);


        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        // Display the Toast Message
        Toast.makeText(this, "Stop Service", Toast.LENGTH_SHORT).show();
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
    }

}

2 个答案:

答案 0 :(得分:0)

如果它无法解析数字,它将抛出NumberFormatException。我通常喜欢在Integer#parseInt中包含Optional次来电,因此我可以提供默认值:

public static Optional<Integer> parseInt(String s) {
    try {
        return Optional.of(Integer.parseInt(s));
    } catch (NumberFormatException ex) {
        return Optional.empty();
    }
}

然后,调用可以提供默认值(或通过#isPresent返回false告知您失败):

int value = parseInt(preferenceTime).orElse(/* some default integer */);

答案 1 :(得分:0)

当然它会失败,因为你想解析“”作为一个int! 试试这个:

String preferenceTime = settings.getString("timer_preference", "0");
int INTERVAL=  (60000 * Integer.parseInt(preferenceTime));

0表示如果我从未在其中设置任何内容,则返回0.它是默认值。

为什么不将它存储为int?!我的意思是:

int preferenceTime = settings.getInteger("timer_preference", 0);
int INTERVAL=  (60000 * preferenceTime);