【问题标题】:Android OS on network main thread exception [duplicate]网络主线程异常上的Android OS [重复]
【发布时间】:2025-12-20 20:05:16
【问题描述】:

我正在开发一个与 asp.net 网络服务连接的 android 应用程序。因为当我测试应用程序时显示响应

Android OS 网络主线程异常”。

我的代码

class GetDetails extends AsyncTask<String, String, String>
{
  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Loading the result... Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
  }

  @Override
  protected String doInBackground(String... args)
  {
     try
     {
       runOnUiThread(new Runnable() {  
         @Override
         public void run() 
         {
           TextView webserviceResponse = (TextView) findViewById(R.id.textView1);
           webserviceResponse.setText("Requesting to server .....");

           //Create Webservice class object
           WebserviceCall com = new WebserviceCall(); 

           // Initialize variables
           String weight   = "18000";
           String fromUnit = "Grams";
           String toUnit   = "Kilograms";

           //Call Webservice class method and pass values and get response
           String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);   

           //Alert message to show webservice response
           Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms", 
           Toast.LENGTH_LONG).show();

           Log.i("AndroidExampleOutput", "----"+aResponse);

           webserviceResponse.setText("Response : "+aResponse);
         }
       }
       );
     }

     finally  {
     }
     return null;
   }
}


protected void onPostExecute(String file_url) {
  // dismiss the dialog once got all details
  pDialog.dismiss();
}

}

【问题讨论】:

    标签: android web-services networkonmainthread


    【解决方案1】:

    将所有代码从 runOnUiThread(new Runnable() {...} 移动到 doInBackground(...)

    作为runOnUiThread(..)代码在主线程中执行

    还有initialized你的ViewsActivity onCreate(..)

    正确:

    class GetDetails extends AsyncTask<String, String, String>
    {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading the result... Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
    
         @Override
         protected String doInBackground(String... args)
         {
             try
             {
                      webserviceResponse.setText("Requesting to server .....");
    
                      //Create Webservice class object
                       WebserviceCall com = new WebserviceCall(); 
    
                              // Initialize variables
                              String weight   = "18000";
                              String fromUnit = "Grams";
                              String toUnit   = "Kilograms";
    
                              //Call Webservice class method and pass values and get response
                              String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);                                
    
                              Log.i("AndroidExampleOutput", "----"+aResponse);
    
                             return aResponse;
                    }
    
             }
            return null;
            }
         }
    
            protected void onPostExecute(String aResponse) {
                // dismiss the dialog once got all details
                pDialog.dismiss();
               //Alert message to show webservice response
                Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms", 
                                Toast.LENGTH_LONG).show();
                webserviceResponse.setText("Response : "+aResponse);
            }
    }
    

    【讨论】:

    • 谢谢 M.D.. 让我试试..
    • @Jocheved 在你的活动onCreate(....)中也初始化了webserviceResponse
    【解决方案2】:

    您好,使用处理程序更新 UI。 处理程序示例

    private Handler handler = new Handler(new Handler.Callback() {  @Override public boolean handleMessage(Message msg) {
        switch( msg.what ){
                    case MSG:                       
                        progressDialog.show();
                        break;
                    case DETACH:
                        progressDialog.dismiss();
                        break;  
                }
        return false; } });
    

    后台调用

    Message m=Message.obtain();
     prepareMessage(m);
     handler.sendMessage(m);
    public void prepareMessage(Message m)
        {
           Bundle b = new Bundle();
           b.putString("message", "Activity Done in background!!!!!!!");
           m.setData(b);
    
        }
    

    【讨论】:

      【解决方案3】:

      doInBackground() 中,您编写了一个 runonUiThread() 方法。

      runOnUIThread() 内部,您正在尝试进行网络调用。这就是它给出 NetworkOnMainThreadException 的原因。

      将该网络调用放在 runOnUiThread() String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit); 但在 doInBackground( ) 我希望它会工作。

      【讨论】:

      • 是否需要删除runonUiThread()
      • 是的...但是您不能从 doInBackGround() 更新 ui 组件..所以请注意您在哪里做什么
      最近更新 更多