【问题标题】:How to connect to network in Android using AsyncTask如何使用 AsyncTask 在 Android 中连接到网络
【发布时间】:2015-03-21 11:18:34
【问题描述】:

我编写如下代码在 Android 中连接网络

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        InitTask task = new InitTask();
        Toast.makeText(getApplicationContext(), task.doInBackground(), Toast.LENGTH_LONG).show();
    }

    private class InitTask extends AsyncTask<Void, Void, String>{
          protected String doInBackground(Void... p){

          // Do network thing...

          return str;
        }
    }
}

我使用了AsyncTask,但出现了NetworkOnMainThreadException

是否允许将 AsyncTask 设为 main Activity 中的内部类? (我在http://developer.android.com/training/basics/network-ops/connecting.html举了个例子)

有什么问题?

【问题讨论】:

  • 您没有正确使用 AsyncTask。仅调用 doInBackground 不会创建线程。

标签: java android android-asynctask


【解决方案1】:

以上所有答案都大致正确,但没有一个是准确的。您需要执行的唯一代码行就是这个。 new InitTask().execute();
无论何时何地您都想执行后台任务,请执行此操作。
也可以看看官方的androidguide
我希望这能回答你的问题。

【讨论】:

  • 你能解释一下new InitTask().execute()吗?没见过这种构造函数。
  • 这在英语中的意思是“通过它的构造函数创建一个新的 InitTask 实例并执行它的方法(doInBackground() 和其他 AsyncTask 方法)”。现在发生这种情况是因为您的 InitTask 类通过 extends 关键字对 AsyncTask 进行了子类化。因此上述执行后台任务的语句。
  • 如果我的上述评论有帮助,请投票给我的答案!
  • 我可以将此方法应用于其他类吗?喜欢new MyClass().myMethod()
  • 这取决于你调用的类。
【解决方案2】:

我使用了 AsyncTask 但发生 NetworkOnMainThreadException。

因为您通过创建InitTask 类对象来调用doInBackground 方法。

在其他线程中执行doInBackground方法调用task.execute()方法启动AsyncTask并使用onPostExecute方法在doInBackground方法执行完成时显示Toast消息:

 @Override
   protected void onPostExecute(String result) {
              Toast.makeText(getApplicationContext(),
               "Task Completed!", Toast.LENGTH_LONG).show();   
   }

【讨论】:

  • 感谢您的回答。当我调用task.execute() 时,会出现错误。我认为它需要参数。我应该传递什么参数?
  • @user3858358:在发布的代码中,您将第一个参数作为 Void 传递,因此 task.execute() 很好。让我知道发生了什么错误?
  • error: no suitable method found for makeText(Context,AsyncTask&lt;Void,Void,String&gt;,int) method Toast.makeText(Context,CharSequence,int) is not applicable (argument mismatch; AsyncTask&lt;Void,Void,String&gt; cannot be converted to CharSequence) method Toast.makeText(Context,int,int) is not applicable (argument mismatch; AsyncTask&lt;Void,Void,String&gt; cannot be converted to int) 我对“无效”和“无效”感到困惑
  • @user3858358:哦!请从 onCreate 中删除 Toast 行,并将 task.execute() 代替 Toast 并将 Toast 移动到 onPostExecute 中,如我的回答所示
  • @user3858358:在 onCreate 中仅使用 InitTask task = new InitTask();task.execute()
【解决方案3】:

是调用.doInBackground(),你必须通过.execute(params);执行Tasks;

【讨论】:

    猜你喜欢
    • 2012-11-20
    • 2011-11-25
    • 1970-01-01
    • 2012-11-20
    • 2012-10-10
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多