【发布时间】:2016-06-07 12:22:31
【问题描述】:
我正在使用 AsyncTask 以便我想要的函数立即执行,而不是等到结束才执行..
但由于某种原因,我不知道为什么它会在所有进程结束时执行!
我查看了其他解决方案,发现 Thread 应该在最后执行,但对于 AsyncTask,它应该在调用时执行..
这是我的代码
private void LogMeIn()
{
string CheckValue;
// Here I call the AsyncTask
new GCM().execute(null,null,null);
//gcmRegID is a public variable and should has GCM value assigned to it by now, but I it is empty as GCM() has not been executed yet
//This is always return empty string
CheckValue = gcmRegID;
}
这是等待结束执行的AsyncTask
//This is the AsyncTask
private class GCM extends AsyncTask<String, String, String> {
private String resp;
private Context context;
@Override
protected String doInBackground(String... params) {
GCMHelper gcmRegistrationHelper = new GCMHelper (
getApplicationContext());
try {
gcmRegID = gcmRegistrationHelper.GCMRegister("123456789");
} catch (Exception e) {
e.printStackTrace();
}
return gcmRegID;
}
}
我试图在 onPreExecute 中调用 GCMRegister,但我收到一个错误,它必须在主线程中
这就像我在兜圈子......
调用必须在主线程中,并且主线程将在函数结束时执行...
中间好像没办法获取GCM代码!!!
如何让这个 AsyncTask 在调用时执行?
谢谢
【问题讨论】:
-
立即执行。但是你对它无能为力。应该更好地查看文档。
-
"gcmRegID 是一个公共变量,现在应该已经分配了 GCM 值" - 不,它不应该,因为你的任务是异步运行的,这意味着它不会阻塞,并且
execute()调用后的行立即继续。 -
你在哪里打电话
LogMeIn()?尝试使用断点。 -
我使用了断点,它没有转到 AsyncTask !我已经尝试了 3 天没有运气!!.. Mike M. 为什么它异步运行?我在这里做错了什么??
标签: java android android-studio android-asynctask google-cloud-messaging