我将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);
}
}
}
答案 0 :(得分:0)
我建议你使用AlarmManager。示例和用法在此处描述:https://developer.android.com/training/scheduling/alarms.html
这是安排重复任务的最佳方式。但如果您的应用已被用户故意杀死,则无法运行。
筛选代码我认为存在设计缺陷。
在onCreate()
- 方法中,您可以设置应用程序并创建计时器以便日后安排。处理onCreate()
后,应用会执行onResume()
等。但是在您的TimerTask
中,您会致电finish()
,这将结束当前的活动(在将来的某个时间,而不是立即)。下一个被激活的意图(在你的TimerTask中)也将首先调用onCreate
方法。开始循环,因为它立即执行它可能会导致一秒钟重复....
因此,您不应该完成活动并为方法scheduleAtFixedRate
添加偏移量。
您还可以检查当前意图(称为活动)是由timertask触发(在其中放入一个额外的)还是从其他任何地方调用它(开始菜单)并且应该创建一个timertask。
答案 1 :(得分:0)
您已将计时器设置为每10秒重复一次,因为您已放置10000毫秒。尝试加入10000毫秒的延迟,然后将repeatInterval变量更改为30000毫秒,使其每30秒重复一次。
我希望这会有所帮助。