0

下面的代码每 30 秒生成 7 个随机数字。

public class MainActivity extends Activity {

Timer timeoutTimer;
final Random myRandom = new Random();
GenerateTask genTask = new GenerateTask();
static String RAN_TEXT = "text";

class GenerateTask extends TimerTask {
    boolean started = false;
    public void run() {
        if (started) {
            System.out.println("generating");
            final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);



           RAN_TEXT = "";

            for(int k=0;k<7;k++){
                RAN_TEXT += myRandom.nextInt(10) + " ";
            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    textGenerateNumber.setText(RAN_TEXT);
                }
            });
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);




     Button buttonGenerate = (Button)findViewById(R.id.generateme);


    buttonGenerate.setOnClickListener(new OnClickListener(){

         @Override
         public void onClick(View v) {
             System.out.println("click");
             if (!genTask.started) {
                 genTask.started=true;
                 timeoutTimer = new Timer();
                 timeoutTimer.scheduleAtFixedRate(genTask, 0, 30000);
             } else {
                 genTask.started=false;
                 timeoutTimer.cancel();
             }
         }
     });  
 }
}

我将申请时间同步到服务器:

http://server10.instaforex.com:2012/TimeService/TimeService.svc?wsdl

如何将服务器时间同步到我的应用程序?

4

2 回答 2

0

为此,您必须使用 Http 连接

见下面的代码

public long getCurrentTimeFromServer() {

    long serverTime = 0;
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(
            "your url");
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result = Utilities.convertinputStreamToString(instream);
            serverTime = Long.parseLong(result);
            // now you have the string representation of the HTML request
            instream.close();
        }

    } catch (Exception e) {
        Log.e("tag", "error", e);
    }

    return serverTime;
}
于 2013-03-14T09:43:30.543 回答
0

为了实现您的目标,您首先需要从服务器获取正确的时间。我认为在服务器端,你有 wsdl,所以在你的客户端(你的应用程序),你需要创建一个进程来连接到服务器并获取时间。

关于如何做到这一点,请在此处查看:http: //www.ibm.com/developerworks/webservices/library/ws-android/index.html

之后,您将在您的应用程序中本地拥有正确的时间,并且您将能够利用该时间做任何事情。

于 2013-03-14T09:44:44.217 回答