【问题标题】:using AsyncTask this way: "new AsyncTask(){" is giving me errors以这种方式使用 AsyncTask:“new AsyncTask(){”给了我错误
【发布时间】:2013-09-09 20:47:09
【问题描述】:

我正在关注 GCM 上的 android 教程,该教程使用了一个名为“doInBackground”的函数,他们的函数定义如下:

private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected String doInBackground(Void... params) {
            //do stuff
        }
        @Override
        protected void onPostExecute(String msg) {
            //do stuff
        }
    }.execute(null, null, null);
}

但是当我将他们自己的代码复制并粘贴到 eclipse 中时,它抱怨说我没有实现 doInBackground。这是因为它期望 doInBackground 具有“对象”的输入参数,并且它无法识别定义的参数,因为它的输入参数是空的。现在,如果我将异步任务声明为一个类,我会将<Void, Void, String> 放在它前面,这会告诉编译器我希望我的 doInBackground 将 Vid 作为输入。但是当我将<Void, Void, String> 放在“new AsyncTask()”前面时:

    private void registerInBackground() {
    new AsyncTask() <Void, Void, String>{

我得到编译器错误:

Syntax error on tokens, delete these tokens

【问题讨论】:

  • 您在execute(null, null, null); 之后缺少}。不知道你有没有注意到。
  • } 在我的实际代码中,我只是在复制到这个网站时错过了它。
  • 这是谷歌的错误吗?当复制/粘贴一些示例代码时,它应该可以正常运行,或者?代码还是一样的,见developer.android.com/google/gcm/client.html#play-services

标签: android android-asynctask


【解决方案1】:

你应该在参数类型规范之后有()

new AsyncTask<Void, Void, String>() { /*Your code(e.g. doInBackground )*/ }.execute();  

【讨论】:

  • 天哪,谢谢你,我快疯了!
【解决方案2】:

试试这个:

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground( Void... voids ) {
        //Do things...
        return null;
    }
}.execute();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多