Android 计时器任务工作不正常

Android 计时器任务工作不正常,android,timertask,Android,Timertask,我将TimerTask设置为每30秒运行一次,但为什么我的TimerTask改为每隔几秒运行一次?我希望我的应用程序每30秒自动重新加载一次。我使用的方法正确吗?我已经面临这个问题很长一段时间了 public class MainActivity extends ActionBarActivity { Timer repeatTask = new Timer(); int repeatInterval = 30000; @Override protected void onCreate(

我将TimerTask设置为每30秒运行一次,但为什么我的TimerTask改为每隔几秒运行一次?我希望我的应用程序每30秒自动重新加载一次。我使用的方法正确吗?我已经面临这个问题很长一段时间了

public class MainActivity extends ActionBarActivity {


Timer repeatTask = new Timer();
int repeatInterval = 30000;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String city = "";

    Intent intent = getIntent();
    pi = intent.getStringExtra("pi");
    Log.d("PI", pi);

    mainListView = (ListView) findViewById(R.id.mainListView);

    cityText = (TextView) findViewById(R.id.cityText);
    condDescr = (TextView) findViewById(R.id.condDescr);
    imgView = (ImageView) findViewById(R.id.condIcon);

    // Create and populate a List of variable names.
    String[] weather = new String[] {};
    ArrayList<String> weatherData = new ArrayList<String>();
    weatherData.addAll(Arrays.asList(weather));

    listAdapter = new WeatherAdapter(this, weatherData);

    JSONWeatherTask task = new JSONWeatherTask();
    task.execute(new String[] { city });

    ImageButton picture = (ImageButton) findViewById(R.id.btnPicturePage);
    picture.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent startPic = new Intent(MainActivity.this,
                    PicturePage.class);
            startPic.putExtra("date", date);
            startPic.putExtra("pi", pi);
            startActivity(startPic);
        }
    });

    repeatTask.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Intent intent = new Intent(MainActivity.this, MainActivity.class);
            intent.putExtra("pi", pi);
            finish();
            startActivity(intent);
        }
        }, 0, repeatInterval);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.selectPi1:
        Toast.makeText(getApplicationContext(),
                "Pi 1 is currently not available", Toast.LENGTH_LONG)
                .show();

        return true;
    case R.id.selectPi2:
        Intent i2 = new Intent(this, MainActivity.class);
        i2.putExtra("pi", "pi2");
        finish();
        startActivity(i2);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Weather doInBackground(String... params) {
        Weather weather = new Weather();
        String data = ((new WeatherHttpClient()).getWeatherData(params[0]));

        List<NameValuePair> params2 = new ArrayList<NameValuePair>();
        params2.add(new BasicNameValuePair("pi", pi));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params2));
        } catch (UnsupportedEncodingException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        HttpClient httpclient = new DefaultHttpClient();
        try {
            response = httpclient.execute(httpPost, responseHandler);
            Log.d("JSON OUT", response);
            if (response == null) {
                showAlertDialog(MainActivity.this);
            }
        } catch (UnknownHostException uhe) {
            uhe.printStackTrace();
        } catch (ClientProtocolException e4) {
            // TODO Auto-generated catch block
            e4.printStackTrace();
        } catch (IOException e4) {
            // TODO Auto-generated catch block
            e4.printStackTrace();
        }

        try {
            weather = JSONWeatherParser.getWeather(data);
        } catch (JSONException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }

        try {
            json = new JSONObject(response);
        } catch (JSONException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        try {
            weatherD = json.getJSONArray(TAG_WEATHER);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            JSONObject c = weatherD.getJSONObject(0);
            temp = c.getString(TAG_TEMP);
            nTemp = temp.replace('*', '°');
            pressure = c.getString(TAG_PRESSURE);
            humid = c.getString(TAG_HUMIDITY);
            ac = c.getString(TAG_AC);
            int aq = Integer.parseInt(ac);
            if (aq <= 150) {
                airq = "Good";
            } else if (aq <= 300) {
                airq = "Moderate";
            } else if (aq <= 500) {
                airq = "Unhealthy";
            } else if (aq <= 700) {
                airq = "Very Unhealthy";
            } else {
                airq = "HARZADOUS!";
            }
            dateO = c.getString(TAG_DATE);
            SimpleDateFormat formatter = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
            Date dateD = null;
            try {
                dateD = formatter.parse(dateO);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            SimpleDateFormat formatter2 = new SimpleDateFormat(
                    "dd/MM/yyyy hh:mm:ss a", java.util.Locale.getDefault());
            date = formatter2.format(dateD);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return weather;

    }

    @Override
    protected void onPostExecute(Weather weather) {
        super.onPostExecute(weather);

        Drawable day = getResources().getDrawable(R.drawable.clear_day);
        Drawable night = getResources().getDrawable(R.drawable.clear_night);
        Drawable cloud = getResources().getDrawable(R.drawable.cloudy);
        Drawable haze = getResources().getDrawable(R.drawable.haze);
        Drawable rain = getResources().getDrawable(R.drawable.rain);
        Drawable thunder = getResources().getDrawable(R.drawable.thunder);

        String code = weather.currentCondition.getIcon();

        if (code.equals("01d") || code.equals("02d")) {
            imgView.setImageDrawable(day);
        } else if (code.equals("01n") || code.equals("02n")) {
            imgView.setImageDrawable(night);
        } else if (code.startsWith("03") || code.startsWith("04")) {
            imgView.setImageDrawable(cloud);
        } else if (code.startsWith("09") || code.startsWith("10")) {
            imgView.setImageDrawable(rain);
        } else if (code.startsWith("11")) {
            imgView.setImageDrawable(thunder);
        } else if (code.startsWith("50")) {
            imgView.setImageDrawable(haze);
        }

        cityText.setText("Cyberjaya" + ", " + weather.location.getCountry()
                + " - " + pi);
        if (weather.currentCondition.getCondition().equals("Clouds")) {
            condDescr.setText("Weather: Cloudy");
            weatherS = "Cloudy";
        } else {
            condDescr.setText("Weather: "
                    + weather.currentCondition.getCondition());
            weatherS = weather.currentCondition.getCondition();
        }
        listAdapter.add("Temperature: " + "\t\t\t\t" + nTemp);
        listAdapter.add("Humidity: " + "\t\t\t\t\t\t" + humid);
        listAdapter.add("Air pressure: " + "\t\t\t\t" + pressure);
        listAdapter.add("Air quality: " + "\t\t\t\t\t" + airq + " (" + ac
                + ")");
        listAdapter.add("Updated on: " + "\t\t\t\t" + date);

        pDialog.dismiss();



        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter(listAdapter);

    }
}
}

我建议您使用AlarmManager。示例和用法如下所述:

这是安排重复任务的最佳方法。但如果你的应用程序被用户故意杀死,它将不会运行

屏蔽你的代码我认为有设计缺陷

在onCreate方法中,您可以设置应用程序并创建计时器以在将来进行调度。处理onCreate后,应用程序将在Resume等上执行。但在您的TimerTask中,您确实调用finish,它将在将来某个时间结束当前活动,而不是立即结束。TimerTask中的下一个激发的意图也将首先调用onCreate方法。开始循环时,由于它会立即执行,因此可能会导致一秒钟的重复。。。。 因此,您不应该完成活动并向scheduleAtFixedRate方法添加偏移量。
您还可以检查调用该活动的当前意图是否由timertask触发,或者是否从其他任何位置的“开始”菜单调用,并且是否应创建timertask。

您已将计时器设置为每10秒重复一次,因为您已将10000毫秒放入。尝试输入10000毫秒的延迟,然后将repeatInterval变量更改为30000毫秒,使其每30秒重复一次


我希望这有帮助

同样的问题,它每秒都会重新加载。