我想在点击按钮后启动计时器并每隔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();
}
error
是TextView
,其中我正在显示一些文字。
我在Asyntask中调用Web服务。所以它不会在按钮点击后执行asynchtask延迟3秒。
我不知道在哪里知道究竟是什么问题。它应该实际执行,我的textview没有每3秒更新一次。
答案 0 :(得分:1)
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);
你可以建议我替代这个,以便我可以执行 AsynchTask在3秒后延迟??
我假设你想在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());
}
}
}
}