gpt4 book ai didi

android - 单击按钮后启动计时器

转载 作者:行者123 更新时间:2023-11-29 01:43:19 25 4
gpt4 key购买 nike

我想在点击按钮后启动计时器并每 3 秒轮询一次。

我正在使用以下代码。

private EditText url;
private Button submit;
private TextView error;
String some_URL;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);

loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}

}
});
private void getStatus() {
// TODO Auto-generated method stub

handler.postDelayed(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
new Class_Poll().execute(some_URL);
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
}
}, 3000);
}
}

private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);

submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());

}


private class Class_Poll extends AsyncTask<String, Void, Void>{

private final HttpClient Client = new DefaultHttpClient();

@Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
Content=executeHttpRequest(some_URL);
return null;
}

@Override
protected void onPostExecute(Void unused) {

JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(Content);

ID=jsonResponse.optString("ID").toString();
name=jsonResponse.optString("Name").toString();
type=jsonResponse.optString("Type").toString();
Status=jsonResponse.optString("Status").toString();

error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);

} catch (JSONException e) {

error.setText(e.toString());
}

//Toast.makeText(getApplicationContext(), "ID:"+ID+" Name:"+name+" Type:"+type+" Status:"+Status, Toast.LENGTH_LONG).show();
}
}

public static String executeHttpRequest(String url)
{
HttpURLConnection urlConnection = null;
try
{

URL httpUrl = new URL(url);
urlConnection = (HttpURLConnection) httpUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Accept", "text/html,text/xhtml,application/xhtml+xml,application/xml;");
urlConnection.setConnectTimeout(10000);
InputStream in = null;

try
{
in = urlConnection.getInputStream();

} catch (NullPointerException e)
{
Log.e("Check", "Request Failed, Check the url");
return null;
}

if (in != null)
{
in = new BufferedInputStream(in);
String response = readStream(in);
Log.e("Check", response + "");

if (response != null && !response.isEmpty())
{
// statusTrace.print(TAG, "Operation executed : " +
// isSuccess(response));
return response;
}
else
{
Log.e("Check", "Request Failed");
}
} else
;//statusTrace.print(TAG, "Request Failed");

} catch (IOException e)
{
Log.e("Check", "Error : " + e.toString());
//statusTrace.print("Error", "Network Error. Check connection and Tuxedo IP");
}

return null;
}

public static String readStream(InputStream in)throws IOException {
// TODO Auto-generated method stub
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();

while (read != null)
{
sb.append(read);
read = br.readLine();
}
return sb.toString();
}

errorTextView,我在其中显示一些文本。

我正在 Asyntask 中调用 Web 服务。因此它不会在按钮单击后延迟 3 秒执行异步任务。

不知道哪里出了问题。它应该实际执行,我的 TextView 不是每 3 秒更新一次。

最佳答案

Timer 在不同的线程上运行,您不应从后台线程调用 AsyncTask。

请阅读线程规则@

http://developer.android.com/reference/android/os/AsyncTask.html

public void scheduleAtFixedRate (TimerTask task, long delay, long period)

Added in API level 1
Schedule a task for repeated fixed-rate execution after a specific delay has passed.

Parameters
task the task to schedule.
delay amount of time in milliseconds before first execution.
period amount of time in milliseconds between subsequent executions.
Throws
IllegalArgumentException if delay < 0 or period <= 0.
IllegalStateException if the Timer has been canceled, or if the task has been scheduled or canceled.

你的延迟是 0。看这个 }, 0, 3000);

can you suggest me an alternative to this so that I can execute AsynchTask at after 3 secs of delay??

我假设您想在延迟 3 秒后调用 asynctask

你可以使用处理程序

 Handler handler = new Handler(): 
handler.postDelayed(new Runnable(){
@Override
public void run() {
// run something after 3 sec delay
}
}, 3000);

编辑:

public class MainActivity extends Activity
{
private EditText url;
private Button submit;
private TextView error;
String Content;
String some_URL;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
});
}
private void getStatus() {
// TODO Auto-generated method stub

handler.postDelayed(new Runnable(){

@Override
public void run() {

new Class_Poll().execute(some_URL);

}
}, 3000);
}


private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);

submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());

}

private class Class_Poll extends AsyncTask<String, Void, String>{


@Override
protected String doInBackground(String... arg0) {
String _response;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(arg0[0]);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
}catch(Exception e)
{
e.printStackTrace();
}

return _response;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);

String ID=jsonResponse.optString("ID").toString();
String name=jsonResponse.optString("Name").toString();
String type=jsonResponse.optString("Type").toString();
String Status=jsonResponse.optString("Status").toString();

error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);

} catch (JSONException e) {

error.setText(e.toString());
}
}

}
}

关于android - 单击按钮后启动计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23053424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com