下面的代码每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
如何将服务器时间同步到我的应用程序?
答案 0 :(得分: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;
}
答案 1 :(得分:0)
为了实现目标,首先需要从服务器获得正确的时间。我在服务器端播种,你有wsdl,所以在你的客户端(你的应用程序),你需要创建一个连接到服务器并获得时间的进程。
关于如何操作,请点击此处:http://www.ibm.com/developerworks/webservices/library/ws-android/index.html
之后,您将在本地应用程序中获得正确的时间,并且您将能够在那段时间内做任何事情。