AsyncTask的Andr​​oid的例子 [英] AsyncTask Android example

查看:143
本文介绍了AsyncTask的Andr​​oid的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读有关AsyncTask的,我尝试了简单的程序如下。但它似乎并没有工作。我怎样才能使它工作?

  com.test包;

进口android.app.Activity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.provider.Settings.System;
进口android.view.View;
进口android.widget.Button;
进口android.widget.TextView;
进口android.view.View.OnClickListener;

公共类AsyncTaskActivity延伸活动{
    按钮BTN;
    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);

        BTN =(按钮)findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener)本);
    }

    公共无效的onClick(视图查看){
        新LongOperation()执行();
    }

    私有类LongOperation扩展的AsyncTask<字符串,太虚,字符串> {
        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            的for(int i = 0;我小于5;我++){
                尝试 {
                    视频下载(1000);
                }赶上(InterruptedException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }
            }
            TextView的TXT =(TextView中)findViewById(R.id.output);
            txt.setText(伏法);
            返回null;
        }

        @覆盖
        保护无效onPostExecute(字符串结果){
        }

        @覆盖
        在preExecute保护无效(){
        }

        @覆盖
        保护无效onProgressUpdate(空...值){
        }
    }
}
 

我只是想在5秒后更改的标签在后台进程。

这是我的main.xml:

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
              机器人:layout_width =FILL_PARENT
              机器人:layout_height =FILL_PARENT
              机器人:方向=垂直>
    <进度
        机器人:ID =@ + ID /进度
        风格=机器人:ATTR / progressBarStyleHorizo​​ntal
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:不确定=假
        机器人:最大=10
        机器人:填充=10dip>
    < /进度>
    <按钮
        机器人:ID =@ + ID /按钮1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=开始进步>
    < /按钮>
    < TextView的机器人:ID =@ + ID /输出
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=替换为/>
< / LinearLayout中>
 

解决方案

确定你正在尝试通过另一个线程访问GUI。这一点,在主,是不是好的做法。

在AsyncTask的在执行一切doInBackground()另一个线程,而无法访问到你的观点是图形用户界面内。

preExecute() postExecute()为您提供访问之前和繁重的任务后,GUI发生在这个新的线程,你甚至可以长时间操作的结果传递给 postExecute()然后显示处理的任何结果。

请参阅这些行,你在以后更新TextView的:

  TextView的TXT =(TextView中)findViewById(R.id.output);
txt.setText(伏法);
 

把它们放在 PostExecute()

您再看到后 doInBackground 完成更新您的TextView文本。

编辑:我注意到,你的onClick监听器不检查,看看哪些观点已经被选定。我觉得要做到这一点是通过switch语句最简单的方法。我有一个完整的类与所有建议下面编辑,以避免混淆。

 进口android.app.Activity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.provider.Settings.System;
进口android.view.View;
进口android.widget.Button;
进口android.widget.TextView;
进口android.view.View.OnClickListener;

公共类AsyncTaskActivity扩展活动实现OnClickListener {

    按钮BTN;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        BTN =(按钮)findViewById(R.id.button1);
        //因为我们实现OnClickListener,我们只需要通过本
        //(很容易)
        btn.setOnClickListener(本);
    }

    公共无效的onClick(视图查看){
        //检测是点击视图
        开关(view.getId()){
        案例R.id.button1:
            新LongOperation()执行();
            打破;
        }
    }

    私有类LongOperation扩展的AsyncTask<字符串,太虚,字符串> {

        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            的for(int i = 0;我小于5;我++){
                尝试 {
                    视频下载(1000);
                }赶上(InterruptedException异常E){
                    Thread.interrupted();
                }
            }
            返回已执行;
        }

        @覆盖
        保护无效onPostExecute(字符串结果){
            TextView的TXT =(TextView中)findViewById(R.id.output);
            txt.setText(伏法); // txt.setText(结果);
            //可能需要更改执行的通过返回的字符串
            //为onPostExecute(),但是这是高达你
        }

        @覆盖
        在preExecute保护无效(){}

        @覆盖
        保护无效onProgressUpdate(空...值){}
    }
}
 

I was reading about AsyncTask, and I tried the simple program below. But it does not seem to work. How can I make it work?

package com.test;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity {
    Button btn;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

I am just trying to change the label after 5 seconds in the background process.

This is my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

解决方案

Ok you are trying to access the GUI via another thread. This, in the main, is not good practice.

The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.

preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.

See these lines where you are later updating your TextView:

TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

put them in PostExecute()

You will then see your TextView text updated after the doInBackground completes.

EDIT: I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.button1);
        // because we implement OnClickListener we only have to pass "this"
        // (much easier)
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {
        // detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            new LongOperation().execute("");
            break;
        }
    }

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

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}

这篇关于AsyncTask的Andr​​oid的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆