将代码移动到AsyncTask
问题描述:
**编辑:解决**将代码移动到AsyncTask
我正在测试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 containts嵌套类LongOperation延伸的AsyncTask。它是我的布局没有正确绑定?
需要一些建议
答
我是否需要移动整个视图以异步任务?我不能 找到相关的文章
=>不,你不应该把整个东西移动到AsyncTask。首先了解AsyncTask的四种不同方法的目的并相应地移动你的东西。
-
onPreExecute()
- 在开始执行之前需要准备的东西。例如,显示进度条或对话框 -
doInBackground()
- 写下长时间运行的操作在此方法中喜欢做一个Web API调用 -
onProgressUpdate()
- 你可以把部分更新此方法来UI。例如1/10那种在进度条输出的 -
onPostExecute()
- UI更新或要进行长时间运行的操作执行后的任何其他操作,即网络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);
}
}
}
答
我想你需要一个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();
}
}
}
答
好的,我弄清了代码..这是我工作的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) {}
}
}
下面的链接可以是有用的: http://stackoverflow.com/questions/9671546 /的AsyncTask-Android的示例 – Drv