使用AsyncTask的方式:“new AsyncTask(){}”会导致错误。

10

我正在跟随一份介绍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具有“Object”类型的输入参数,而它不能识别已定义的那个,因为它的输入参数是void类型。现在,如果我将异步任务声明为一个类,我会在其前面放置<Void,Void,String>,这将告诉编译器我希望我的doInBackground有Void作为输入。但是当我像这样在“new AsyncTask()”前面放置<Void,Void,String>时:
    private void registerInBackground() {
    new AsyncTask() <Void, Void, String>{

我遇到了编译器错误:

Syntax error on tokens, delete these tokens

你的 execute(null, null, null); 后面缺少一个 }。不知道你有没有注意到。 - Varun
} 在我的实际代码中,我只是在复制到这个网站时错过了它。 - Siavash
谷歌犯了一个错误吗?当复制/粘贴一些示例代码时,它不应该出现错误,对吧?代码仍然是相同的,请参见http://developer.android.com/google/gcm/client.html#play-services - user2345998
2个回答

28

在参数类型说明后面应该加上():

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

2
哇塞,谢谢你!我都快疯了! - Siavash

10

试试这个:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接