30 초마다 실행되도록 TimerTask를 설정했지만 대신 TimerTask가 몇 초마다 실행되는 이유는 무엇입니까? 내 앱이 30 초마다 자동으로 다시로드되기를 원할 것입니다. 내가 사용하고있는 방법이 맞습니까? 꽤 오래 동안이 문제에 직면 해왔다.TimerTask가 제대로 작동하지 않습니다.
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);
}
}
}
동일한 문제가 발생하면 매 초마다 다시로드됩니다. – Benz
@firaga 어쩌면 업데이트가 도움이 될 것입니다 .... – matcauthon