网络上的主线程异常

网络上的主线程异常

本文介绍了调用WebService时,网络上的主线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个java类:

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity
{
private static final String SOAP_ACTION = "http://tempuri.org/findContact";

private static final String OPERATION_NAME = "findContact";// your webservice web method name

private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

private static final String SOAP_ADDRESS = "http://10.0.2.2:20959/test/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.textView);

    button=(Button)findViewById(R.id.button);

    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,     OPERATION_NAME);
            PropertyInfo propertyInfo = new PropertyInfo();
            propertyInfo.type = PropertyInfo.STRING_CLASS;
            propertyInfo.name = "eid";

            edata =(EditText)findViewById(R.id.editText);
            studentNo=edata.getText().toString();

            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();
                tvData1.setText(response.toString());
            }  catch (Exception exception)   {
                tvData1.setText(exception.toString()+"  Or enter number is not Available!");
            }

            tvData1 = (TextView)findViewById(R.id.textView);

        }
    });


}

}

这调用webservice的我在C#创建。和IM使用Android Studio创建调用此WebService的应用程序。

Which calls a webservice i created in C#. And im using Android Studio to create an application that call this webservice.

但是当我运行它,我得到这个错误:

But when i run it i got this error:

android.os.NetworkOnMainThreadException

BTW我在清单中增加了互联网的权限。

BTW I added the internet permission in the manifest.

如何解决此问题?

推荐答案

该目标应用蜂窝SDK 或更高版本会抛出 Networkonmainthreadexception 。早期版本被允许做这个主线程的网络,但它在很大程度上鼓励()。基本上,这是通过请求从 UI线程这会破坏用户体验的网络访问,由于这些往往是昂贵的操作造成的。

Applications which target Honeycomb SDK or higher will throw Networkonmainthreadexception. Earlier versions are allowed to do networking on this main thread but it is heavily discouraged (see ‘Keeping Your App Responsive’). Basically this is caused by requesting network access from the UI thread which would disrupt the user experience due to these often expensive operations.

相反,这些操作都需要发生在工作线程,而要做到,所以你需要使用某种类型的线程或处理程序。最常见的是一个的AsyncTask

Instead, these operations need to happen on a worker thread, and to do so you need to use some sort of thread or handler. The most common being an AsyncTask.

请参阅,在
Android系统这个文件的使用,但它基本上可以归结为以下实现:

See http://developer.android.com/reference/android/os/AsyncTask.html for theandroid documented usage of this but it basically boils down to the following implementation:

延伸AsyncTask的私有子类,可以实现下列方法:

A private subclass which extends AsyncTask which Implements the following methods:


  1. 上preExecute - 任务之前调用UI线程上执行,用于设置东西了(例如显示进度条)

  1. onPreExecute – Invoked on the UI thread before the task is executed and is used for setting stuff up (e.g showing the progress bar)

doInBackground - 要执行它后立即开火preExecute实际运行

doInBackground – The actual operation you want to perform which is fired immediately after onPreExecute

onPostExecute - 在UI线程上调用doInBackground完成后。这需要在结果从doInBackground作为参数,然后可以在UI线程上使用。

onPostExecute – Invoked on the UI thread after doInBackground completes. This takes in the result from doInBackground as a parameter and can then be used on the UI thread.

这是AsyncTask的用于其未在UI线程上允许的,如操作:

An AsyncTask is used for operations which aren’t permitted on the UI thread such as:


  • 打开一个套接字连接

  • 的HTTP请求(如了HTTPClient和HttpURLConnection类)

  • 试图连接到远程MySQL数据库

  • 下载文件

您当前code是坐在这将在UI线程上创建一个方法(将抛出一个 NetworkOnMainThreadException ),所以你需要移动你的code在一个线程的不可以主/ UI线程上运行,从阻塞UI,而您的操作去阻止它。

Your current code is sitting in a method which will be created on the UI thread (which will throw a NetworkOnMainThreadException), so you need to move your code over to a thread not running on the main/UI thread to stop it from blocking the UI whilst your operations go on.

这篇关于调用WebService时,网络上的主线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:28