2012-01-20 2 views
-1

내가 알고 싶은 클래스에 대한 자바 스크립트의 setInterval에 대한 안드로이드 이에 상응하는 http로 예를 들어, 일정한 간격으로 예를 들어 10 초 동안 서버에 데이터를 게시하려고하는 코드는 아래 코드입니다.android equivalent에 대한 자바 스크립트의 클래스에 대한

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tv=(TextView)findViewById(R.id.textview); 
    text = ""; 

    try { 
     postData(); // display the data 

    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 



    public void postData() throws JSONException{ 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     final Random myRandom = new Random(); 
     HttpPost httppost = new HttpPost("http://mywebpage.com/index.php?id="+myRandom.nextInt(100000)); 
     JSONObject json = new JSONObject(); 

     try { 

      JSONArray postjson=new JSONArray(); 
      postjson.put(json); 

      // Post the data: 
      StringEntity se = new StringEntity("JSON: " + json.toString()); 
      se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
      httppost.setEntity(se); 

      // Execute HTTP Post Request 
      System.out.print(json); 
      HttpResponse response = httpclient.execute(httppost); 

      // for JSON: 
      if(response != null) 
      { 
       InputStream is = response.getEntity().getContent(); 

       BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
       StringBuilder sb = new StringBuilder(); 

       String line = null; 
       try { 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
        try { 
         is.close(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
       text = sb.toString(); 
      } 

      tv.setText(text); 

     }catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     }   



    int initialDelay = 1000; 
    int period = 5000; 
    Timer timer = new Timer(); 
    TimerTask task = new TimerTask() { 
    public void run() { 
    Looper.prepare(); 
    try { 
    postData(); 
    } 
    catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 
    Looper.loop(); 
    Looper.myLooper().quit(); 
    } 
    }; 
    timer.scheduleAtFixedRate(task, initialDelay, period); 



    } 

모든 답장을 환영합니다 :)

로그 파일 :

01-21 02:07:30.441: W/dalvikvm(575): threadid=7: thread exiting with uncaught exception (group=0x4001d800) 
01-21 02:07:30.451: E/AndroidRuntime(575): FATAL EXCEPTION: Timer-0 
01-21 02:07:30.451: E/AndroidRuntime(575): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 
01-21 02:07:30.451: E/AndroidRuntime(575): at android.view.ViewRoot.checkThread(ViewRoot.java:2802) 
01-21 02:07:30.451: E/AndroidRuntime(575): at android.view.ViewRoot.invalidateChild(ViewRoot.java:607) 
01-21 02:07:30.451: E/AndroidRuntime(575): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633) 
01-21 02:07:30.451: E/AndroidRuntime(575): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505) 
01-21 02:07:30.451: E/AndroidRuntime(575): at android.view.View.invalidate(View.java:5139) 
01-21 02:07:30.451: E/AndroidRuntime(575): at android.widget.TextView.checkForRelayout(TextView.java:5364) 
+1

읽기가 먼저 ... 나중에 코드를 작성 ... 내가 developer.android.com 웹 사이트에서 전체 dev에 가이드를 읽어 의미 .. 그럼 당신은 당신이 UI 스레드에서 인터넷 작업을 어떻게 방지 할 수있는 안된다는 knwon한다 그것 asynctask/intentservice – Selvin

답변

2

나는 이것이 당신이 찾고있는 무엇을 생각 : Android scheduleAtFixedRate

+0

int initialDelay = 1000; int 기간 = 5000; 타이머 타이머 = 새 타이머(); TimerTask task = new TimerTask() { 공개 무효 실행() { Looper.prepare(); 시도 { \t \t \t \t \t postData(); \t \t \t \t} 캐치 (JSONException 전자) { \t \t \t \t \t // TODO) (catch 블록을 \t \t \t \t \t e.printStackTrace를 자동 생성; \t \t \t \t Looper.loop(); Looper.myLooper(). quit(); } }; timer.scheduleAtFixedRate (task, initialDelay, period); 앱. 충돌하는거야? – arjun

+0

앱이 충돌 할 때 LogCat에서 얻게되는 결과는 무엇입니까? – bschultz

+0

게시물에 로그를 추가했습니다. pls check. – arjun

0

나는 생각한다, 당신이 사용할 수있는 내 클럭 클래스. 타이밍을 시작/중지하고 등록 된 TextView 필드에 시간 및/또는 날짜를 표시합니다.

import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 
import android.os.Handler; 
import android.widget.TextView; 
/** 
* The class for creating and refreshing many different fields on different layouts, 
* that can hold actual time and/or date in different formats 
* The formats should be as in http://developer.android.com/reference/java/text/SimpleDateFormat.html. 
* Only present and visible fields are being actualized, so there is no need to clean the clock list after closing an activity 
* 
* Examples of use: 
* 
*  Clock.registerClock((TextView) findViewById(R.id.TimeField), "HH:mm"); 
*  Clock.registerClock((TextView) findViewById(R.id.DateField), "d.M.yyyy EEE"); 
*  Clock.start(10000L); 
* 
* @author Petr Gangnus 
*/ 
public final class Clock { 
    /** 
    * the handler that works instead of timer and supports UI 
    */ 
    static private Handler handler = new Handler(); 
    /** 
    * the interval of the time refreshing 
    */ 
    static private long refreshStep; 

    /** 
    * pairs TextView timer+time/date format 
    */ 
    private TextView clockFace; 
    private String format; 
    private Clock(TextView clockFace, String format){ 
     this.clockFace=clockFace; 
     this.format=format; 
    } 
    // here is the list of views containing the visual timers that should be held actual 
    static private ArrayList<Clock> clocks=new ArrayList<Clock>(); 
    /** 
    * fills all timer fields by actual time value, according to their formats. 
    */ 
    static private Runnable mUpdateTimeTask = new Runnable() { 
     public void run() { 
      for(Clock clock:clocks){ 
       showActualTimeDate(clock); 
      } 
      handler.postDelayed(this,refreshStep); 
     } 
    }; 

    //============================================ public members ==================================================================== 
    /** 
    * add a clock to the list of updating clocks 
    * @param clockFace - the place where the time or date will be shown 
    * @param format - the format of the time/date 
    * @return 
    */ 
    public static boolean registerClock(TextView clockFace, String format){ 
     if (clockFace==null) return false; 
     if(clocks.contains(clockFace)){ 
      // old clockFace 
      clocks.get(clocks.indexOf(clockFace)).format=format; 
     } else { 
      // new clockFace 
      clocks.add(new Clock(clockFace, format)); 
     } 
     return true; 
    } 
    /** 
    * remove a clock from the updating list 
    * @param clockFace 
    * @return 
    */ 
    public static boolean unRegisterClock(TextView clockFace){ 
     if (clockFace==null) return false; 
     if(clocks.contains(clockFace)){ 
      // found clockFace 
      clocks.remove(clocks.indexOf(clockFace)); 
     } else { 
      // not found clockFace 
      return false; 
     } 
     return true; 
    } 
    /** 
    * put in the "place" the actual date/time in the appropriate "format" 
    * @param place 
    * @param format 
    */ 
    public static void showActualTimeDate(Clock clock){ 
     if (clock.clockFace==null) return; 
     if (clock.clockFace.getVisibility()!=TextView.VISIBLE) return; 
     Date thisDate=new Date(); 
     SimpleDateFormat df=new SimpleDateFormat(clock.format); 
     clock.clockFace.setText(df.format(thisDate)); 
    } 
    /** 
    * start the ticking for all clocks 
    * @param step the tick interval 
    */ 
    public static void start(long step) { 
     refreshStep=step; 
     handler.removeCallbacks(mUpdateTimeTask); 
     handler.postDelayed(mUpdateTimeTask, 0); 
    } 
    /** 
    * Stopping ticking all clocks (not removing them) 
    * the calling could be put somewhere in onStop 
    */ 
    public static void stop() { 
     handler.removeCallbacks(mUpdateTimeTask); 
    } 
} 
관련 문제