【问题标题】:moving code to AsyncTask将代码移动到 AsyncTask
【发布时间】:2016-07-06 04:57:17
【问题描述】:

**编辑:已解决**

我正在测试有关 AsyncTask 功能的示例代码。但是 dobackGround() 方法没有调用代码。我接受了一些帖子的帮助并重构了我的代码,但它仍然无法正常工作

这是主布局

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1">
    </EditText>

    <Button
        android:text="Get Name"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>

    <TextView
        android:text="from Web service"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

MainActivity.java

public class MainActivity  extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}

WebServiceActivity.java

public class WebServiceActivity extends Activity implements View.OnClickListener {

    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {

        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.textView1);
            txt.setText("Executed"); // txt.setText(result);

        }

        @Override
        protected void onPreExecute() {}

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

WebServiceActivity 包含扩展 AsyncTask 的内部类 LongOperation。是不是我的布局没有正确绑定?

需要一些建议

【问题讨论】:

标签: android android-asynctask android-studio-2.0


【解决方案1】:

我是否需要将整个视图移动到异步任务?我不能 查找相关帖子

=> 不,您不应该将所有内容移至 AsyncTask。首先了解 AsyncTask 四种不同方法的用途,并相应地移动你的东西。

  • onPreExecute() - 在执行开始之前你想要准备的东西。例如显示进度条或对话框
  • doInBackground() - 在此方法中写下长时间运行的操作,例如进行 Web API 调用
  • onProgressUpdate() - 您可以通过此方法将部分更新推送到 UI。例如 1/10 种输出进度条
  • onPostExecute() - UI 更新或任何其他您想要在长时间运行的操作(即 Web API 调用)后执行的操作

其他几点:

  • 这些天 AsyncTask 并没有被太多使用,而是使用了一些其他方法。

  • 有一些第三方和最好的库可以帮助您实现长时间运行的任务。示例库是 Retrofit、OkHttp

  • 目前开发人员已经开始使用响应式方法,因此使用 RxJava、RxAndroid 库。

【讨论】:

    【解决方案2】:

    我认为您需要一个 AsyncTask 的示例,所以这里是。这是 loginTask 使用 AsyncTask 的示例。希望对你有帮助...

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.content.res.Resources;
    import android.net.ConnectivityManager;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.widget.Toast;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    /**
      * Created by jatin khattar on 01-10-2015.
     */
    public class LoginTask extends AsyncTask<String, Integer, String> {
    
    
    Context context;
    User user;
    private ConnectivityManager conMgr;
    private Resources r;
    private ProgressDialog dialog;
    private Session session;
    
    
    private final static String API_PARAM_TYPE="type";
    private final static String API_PARAM_EMAIL="email";
    private final static String API_PARAM_PASSWORD="password";
    
    
    
    public LoginTask(Context context, User user, ConnectivityManager conMgr){
        this.context = context;
        this.user = user;
        this.conMgr = conMgr;
        r=context.getResources();
        session=new Session(context);
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog=ProgressDialog.show(context, r.getString(R.string.progress_message), "Please Wait");
    }
    
    @Override
    protected String doInBackground(String... params) {
        API api=new API(this.context, conMgr);
        api.setAPI("user");
        api.setAction("login");
        api.setParam(API_PARAM_TYPE, "general");
        api.setParam(API_PARAM_EMAIL, user.email);
        api.setParam(API_PARAM_PASSWORD, user.pass);
        String result=api.process();
        Log.d("API Response", result);
        return result;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        dialog.dismiss();
        try {
            JSONObject res=new JSONObject(result);
            if(res.getBoolean("success")){
                session.CreateSession(res.getInt("id"), res.getString("name"), res.getString("auth_key"), res.getString("email"));
                Toast.makeText(this.context, "Logged in Successfully", Toast.LENGTH_LONG).show();
                Intent intnt = new Intent(context, MainActivity.class);
                intnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                context.startActivity(intnt);
            }else{
                if(res.has("message")){
                    Toast.makeText(this.context, res.getString("message"), Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(this.context, r.getString(R.string.error_message_unknown), Toast.LENGTH_SHORT).show();
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this.context, r.getString(R.string.error_invalid_response_message), Toast.LENGTH_SHORT).show();
        }
    
    }
    
    }
    

    【讨论】:

      【解决方案3】:

      你不需要把整个代码放在asynctask里面,你必须把网络操作代码放在asynctask的doInBackground()里面。

      public class MainActivity extends Activity
      {
          /**
           * Called when the activity is first created.
           */
          private static final String SOAP_ACTION ="http://tempuri.org/HelloWorld";
      
          private static final String OPERATION_NAME = "findContact";
      
          private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
      
          private static final String SOAP_ADDRESS = "http://10.0.2.2:31736/WebSite3/Service.asmx";
          TextView tvData1;
          EditText edata;
          Button button;
          String studentNo;
      
      
          @Override
          public void onCreate(Bundle savedInstanceState)
          {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              tvData1 = (TextView) findViewById(R.id.textView1);
              button = (Button) findViewById(R.id.button1);
              edata = (EditText) findViewById(R.id.editText1);
      
              button.setOnClickListener(new OnClickListener()
              {
      
                  public void onClick(View v)
                  {
                      studentNo = edata.getText().toString();
      
                      new BackgroundTask().execute();
                  }
              });
      
          }
      
      
          class BackgroundTask extends AsyncTask<String, Void, String>
          {
      
              @Override
              protected String doInBackground(String... params)
              {
                  SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
                  PropertyInfo propertyInfo = new PropertyInfo();
                  propertyInfo.type = PropertyInfo.STRING_CLASS;
                  propertyInfo.name = "eid";
      
                  request.addProperty(propertyInfo, studentNo);
      
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                  envelope.dotNet = true;
                  envelope.setOutputSoapObject(request);
      
                  HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
      
                  try
                  {
                      httpTransport.call(SOAP_ACTION, envelope);
                      Object response = envelope.getResponse();
                      return response.toString();
                  } catch (Exception exception)
                  {
                      return exception.toString() + "  Or enter number is not Available!";
                  }
              }
      
              @Override
              protected void onPostExecute(String s)
              {
                  tvData1.setText(s);
              }
          }
      
      }
      

      【讨论】:

        【解决方案4】:

        好的,我找到了代码..这是我的 Asyntask 工作代码。只需要一个主类和一个内部类

        Activity_main.xml

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/editText1">
            </EditText>
        
            <Button
                android:text="Get Name"
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </Button>
        
            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </TextView>
        
            </LinearLayout>
        

        MainActivity.java

        public class MainActivity  extends Activity
        {
        
        TextView tvData1;
        EditText edata;
        Button button;
        
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        
            tvData1 = (TextView)findViewById(R.id.textView1);
        
        
            button=(Button)findViewById(R.id.button1);
        
            button.setOnClickListener(new OnClickListener() {
        
                public void onClick(View v) {
                    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) {
                        Thread.interrupted();
                    }
                }
                return "executed";
            }
        
            @Override
            protected void onPostExecute(String result) {
                tvData1.setText(result);
            }
        
            @Override
            protected void onPreExecute() {}
        
            @Override
            protected void onProgressUpdate(Void... values) {}
        }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-26
          • 2013-09-28
          • 1970-01-01
          • 1970-01-01
          • 2020-08-28
          • 2021-02-07
          • 1970-01-01
          相关资源
          最近更新 更多