-2

私が取り組んでいるAndroidアプリ用のこのコードがあります:

package com.exercise.AndroidInternetTxt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidInternetTxt extends Activity {

    TextView textMsg, textPrompt, textSite;
    final String textSource = "http://www.xxx/s.php";


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textPrompt = (TextView)findViewById(R.id.textprompt);
        textMsg = (TextView)findViewById(R.id.textmsg);
        textSite = (TextView)findViewById(R.id.textsite);

        //textPrompt.setText("Asteapta...");


        URL textUrl;
        try {
            textUrl = new URL(textSource);
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
            String StringBuffer;
            String stringText = "";
            while ((StringBuffer = bufferReader.readLine()) != null) {
                stringText += StringBuffer;
            }
            bufferReader.close();
            textMsg.setText(stringText);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            textMsg.setText(e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            textMsg.setText(e.toString());
        }


        //textPrompt.setText("Terminat!");

    }

}

正常に動作し、.php ファイルからテキストを出力します。10秒ごとに自動更新したいのですが、その方法がわかりません。これを解決するのを手伝ってもらえますか? ありがとう!

4

2 に答える 2

1

これはここまでに何度も答えられるべきでした。これが私がそれをする方法です。

TimerTask fileProcessTask = new TimerTask(){

        @Override
        public void run() {
            //put your code to process the url here  
            processFile();

        }

    };

        Timer tm = new Timer();
        tm.schedule(fileProcessTask, 10000L);

動作するはずです

于 2012-05-24T18:33:20.807 に答える
1

タイマー タスクは、別のスレッドを作成し、元のスレッドのみがそのビューにアクセスできるため、機能しません。

Android の場合、これを行うための推奨される方法は、ハンドラーを使用することです。イーサ

textMsg.post( new Runnable(){

     public void run(){
            doProcessing();
            testMesg.setText("bla");
            testMsg.postDelayed(this,(1000*10));
     }
};

または Handler クラスの別のインスタンスを持つ

Handler mHanlder = new Handler();
mHandler.post(runnable);
于 2012-05-24T20:02:46.473 に答える