gpt4 book ai didi

android - 异步任务奇怪的行为

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:04:59 25 4
gpt4 key购买 nike

我在使用 asynctask 时遇到了一些奇怪的警告。我正在学习 GCM,所以我尝试使用 asynctask。这是警告:

Type safety: The method execute(Object...) belongs to the raw type AsyncTask. References to generic type AsyncTask<Params,Progress,Result> should be parameterized

我想了解这个警告的含义。它是关于线程的。为什么它不安全?这是什么原料?

这是我的代码:

private void registerInBackground() {
// TODO Auto-generated method stub



new AsyncTask() {
@Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;

// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();

// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.

// Persist the regID - no need to register again.
storeRegistrationId(getApplicationContext(), regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
} @Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), ""+result.toString(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);



}

谢谢

最佳答案

AsyncTask 是一个 generic Class可以参数化。该警告意味着您应该明确命名参数。

AsyncTask 定义为 AsyncTask<Params,Progress,Result> , 它需要 3 个参数 Params , ProgressResult可以是任何类型/类。

在上面的代码中,您在 doInBackground() 中返回了一个字符串. doInBackground() 的返回值是 AsyncTask 的第三个参数(Result)。

要使警告消失,请实现您的 AsyncTask像这样:

new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
String message = "";

//do something

return message;
}

@Override
protected void onPostExecute(String result) {

}
}.execute();

关于android - 异步任务奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20679246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com