【发布时间】:2017-07-01 20:24:31
【问题描述】:
我正在尝试在 android Service 中使用 AsyncTask,但它不起作用。有人可以帮助我吗?我正在使用片段,我是新手。提前致谢。错误:无法解析方法。这是我的实现。
public class MyService extends Service implements Runnable {
final String numeroPorta = "80";
final String nomeParametro = "num";
String respostaServidor;
private boolean ativo;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startID) {
ativo = true;
new Thread(this, "MyService" + startID).start();
return super.onStartCommand(intent, flags, startID);
}
@Override
public void run() {
myService();
}
@Override
public void onDestroy() {
ativo = false;
}
public void myService() {
new Thread() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (enderecoIP.length() > 0 && numeroPorta.length() > 0 && !Objects.equals(valorParametro, "0")) {
new HttpRequestAsyncTask(getApplicationContext(), valorParametro, enderecoIP, numeroPorta, nomeParametro).execute();
}
}
});
}
}.start();
}
public class HttpRequestAsyncTask extends AsyncTask<Void, Void, Void> {
private String requisicaoResposta, enderecoIP, numeroPorta;
private Context contexto;
private AlertDialog alerta;
private String parametro, valorParametro;
HttpRequestAsyncTask(Context contexto, String valorParametro, String enderecoIP, String numeroPorta, String parametro) {
this.contexto = contexto;
alerta = new AlertDialog.Builder(this.contexto)
.setTitle("Resposta HTTP:")
.setCancelable(true)
.create();
this.enderecoIP = enderecoIP;
this.numeroPorta = numeroPorta;
this.valorParametro = valorParametro;
this.parametro = parametro;
}
@Override
protected Void doInBackground(Void... voids) {
alerta.setMessage("Dados enviados, aguardando resposta do servidor...");
if (!alerta.isShowing()) {
alerta.show();
}
requisicaoResposta = sendRequest(valorParametro, enderecoIP, numeroPorta, parametro);
return null;
}
@Override
protected void onPostExecute(Void avoid) {
alerta.setMessage(requisicaoResposta);
if (!alerta.isShowing()) {
alerta.show();
}
}
@Override
protected void onPreExecute() {
alerta.setMessage("Enviando dados ao servidor, por favor aguarde...");
if (!alerta.isShowing()) {
alerta.show();
}
}
}
}
【问题讨论】:
-
您正在尝试在服务中调用
runOnUiThread;此方法仅在 Activity 中可用。就此而言,在服务中您甚至不需要使用 AsyncTask,只需使用您创建的线程来发出请求。
标签: android service android-asynctask