2014-09-17 2 views
0

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); 

    } 
} 
} 

답변

0

나는 AlarmManager를 사용하는 것이 좋습니다. 여기에 예제와 사용법이 설명되어 있습니다. https://developer.android.com/training/scheduling/alarms.html

반복 작업을 예약하는 가장 좋은 방법입니다. 앱이 사용자에 의해 의도적으로 삭제 된 경우에는 실행되지 않습니다.


디자인 상 결함이 있다고 생각합니다.

onCreate() -method에서는 응용 프로그램을 설정하고 나중에 예약 할 타이머를 만듭니다. onCreate()을 처리 한 후 앱은 onResume() 등을 실행합니다. 그러나 TimerTask에서 현재 활동을 끝내게 될 finish()으로 전화를 겁니다. 다음 발사 된 의도 (TimerTask에서)도 먼저 onCreate 메서드를 호출합니다. 루프를 시작하고 즉시 수행하기 때문에 1 초 반복으로 이어질 수 있습니다 .... 따라서 작업을 완료하고 메서드 scheduleAtFixedRate에 오프셋을 추가하면 안됩니다. 또한 현재 인 텐트 (활동 호출)가 timertask에 의해 해고 되었다면 (여분을 넣음) 다른 곳 (시작 메뉴)에서 호출되어 timertask를 작성해야하는지 확인할 수 있습니다.

+0

동일한 문제가 발생하면 매 초마다 다시로드됩니다. – Benz

+0

@firaga 어쩌면 업데이트가 도움이 될 것입니다 .... – matcauthon

0

10000 밀리 초를 입력 했으므로 타이머를 10 초마다 반복하도록 설정했습니다. 10000 밀리 초와 같은 지연 시간을 넣은 다음 repeatInterval 변수를 30000 밀리 초로 변경하여 매 30 초마다 반복되도록하십시오.

이 정보가 도움이되기를 바랍니다.

관련 문제