Android 将代码移动到异步任务

Android 将代码移动到异步任务,android,android-asynctask,android-studio-2.0,Android,Android Asynctask,Android Studio 2.0,**编辑:已解决** 我正在测试异步任务功能的示例代码。但是dobackGround()方法没有调用代码。我接受了一些帖子的帮助并重构了我的代码,但它仍然不起作用 这是主布局 <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText1"> </EditText>

**编辑:已解决**

我正在测试异步任务功能的示例代码。但是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>
WebServiceActivity.java

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

    }
}
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) {}
    }
}
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) {}
}
}
公共类WebServiceActivity扩展活动实现View.OnClickListener{
按钮btn;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(按钮)findViewById(R.id.button1);
btn.setOnClickListener(此);
}
公共void onClick(视图){
开关(view.getId()){
案例R.id.button1:
新建LongOperation()。执行(“”);
打破
}
}
私有类LongOperation扩展了异步任务{
@凌驾
受保护的字符串doInBackground(字符串…参数){
对于(int i=0;i<5;i++){
试一试{
睡眠(1000);
}捕捉(中断异常e){
Thread.interrupted();
}
}
返回“已执行”;
}
@凌驾
受保护的void onPostExecute(字符串结果){
TextView txt=(TextView)findViewById(R.id.textView1);
txt.setText(“已执行”);//txt.setText(结果);
}
@凌驾
受保护的void onPreExecute(){}
@凌驾
受保护的void onProgressUpdate(void…值){}
}
}
WebServiceActivity包含扩展AsyncTask的内部类LongOperation。是我的布局没有正确绑定吗

需要一些建议吗

是否需要将整个视图移动到异步任务?我不能 寻找相关职位

=>不,您不应该将整个内容移动到AsyncTask。首先理解异步任务的四种不同方法的目的,并相应地移动您的东西

  • onPreExecute()
    -执行开始前需要准备的内容。例如,显示进度条或对话框
  • doInBackground()
    -用这种方法写下长时间运行的操作,比如进行web API调用
  • onProgressUpdate()
    -您可以通过此方法将部分更新推送到UI。例如,进度条中的1/10种输出
  • onPostExecute()
    -UI更新或任何其他要执行长时间运行操作(即web API调用)的后期执行的操作
其他一些要点:

  • 如今,AsyncTask并没有被广泛使用,而是被用于其他一些方法

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

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


    • 您不需要将整个代码放入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);
              }
          }
      
      }
      
      公共类MainActivity扩展活动
      {
      /**
      *在首次创建活动时调用。
      */
      私有静态最终字符串SOAP_ACTION=”http://tempuri.org/HelloWorld";
      私有静态最终字符串操作\u NAME=“findContact”;
      私有静态最终字符串WSDL\u TARGET\u NAMESPACE=”http://tempuri.org/";
      私有静态最终字符串SOAP_地址=”http://10.0.2.2:31736/WebSite3/Service.asmx";
      文本视图tvData1;
      EditText-edata;
      按钮;
      弦乐学生号;
      @凌驾
      创建时的公共void(Bundle savedInstanceState)
      {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      tvData1=(TextView)findViewById(R.id.textView1);
      按钮=(按钮)findViewById(R.id.button1);
      edata=(EditText)findViewById(R.id.editText1);
      setOnClickListener(新的OnClickListener()
      {
      公共void onClick(视图v)
      {
      studentNo=edata.getText().toString();
      新建BackgroundTask().execute();
      }
      });
      }
      类BackgroundTask扩展了AsyncTask
      {
      @凌驾
      受保护的字符串doInBackground(字符串…参数)
      {
      SoapObject请求=新的SoapObject(WSDL\u目标\u命名空间、操作\u名称);
      PropertyInfo PropertyInfo=新的PropertyInfo();
      propertyInfo.type=propertyInfo.STRING\u类;
      propertyInfo.name=“eid”;
      request.addProperty(propertyInfo,studentNo);
      SoapSerializationEnvelope=新的SoapSerializationEnvelope(SoapEnvelope.VER11);
      envelope.dotNet=true;
      envelope.setOutputSoapObject(请求);
      HttpTransportSE httpTransport=新的HttpTransportSE(SOAP\U地址);
      尝试
      {
      调用(SOAP_操作,信封);
      对象响应=envelope.getResponse();
      返回response.toString();
      }捕获(异常)
      {
      返回异常。toString()+“或输入数字不可用!”;
      }
      }
      @凌驾
      受保护的void onPostExecute(字符串s)
      {
      tvData1.setText(s);
      }
      }
      }
      
      我想您需要一个AsyncTask的示例,这里就是。这是一个使用AsyncTask的loginTask示例。希望它能帮助你

      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();
          }
      
      }
      
      }
      
      导入android.app.ProgressDialog;
      导入android.content.Context;
      导入android.content.Intent;
      导入android.content.res.Resources;
      导入android.net.ConnectivityManager;
      导入android.os.AsyncTask;
      导入android.util.Log;
      导入android.widget.Toast;
      导入org.json.JSONException;
      导入org.json.JSONObject;
      /**
      *由jatin khattar于2015年10月1日创建。
      */
      酒吧
      
      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) {}
      }
      }