在服务中运行 AsyncTask - Android
Posted
技术标签:
【中文标题】在服务中运行 AsyncTask - Android【英文标题】:Run AsyncTask in Service - Android 【发布时间】: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,只需使用您创建的线程来发出请求。
【参考方案1】:
看看这段代码是否可行..
public class MyService extends Service
@Override
public IBinder onBind(Intent arg0)
return null;
@Override
public int onStartCommand(Intent intent,int flags,int startId)
//We want this service to continue running until it is explicitly
//stopped,so return sticky.
Toast.makeText(this, "ServiceStarted",Toast.LENGTH_LONG).show();
try
new DoBackgroundTask().execute(new URL(""), new URL(""));
catch (MalformedURLException e)
e.printStackTrace();
return START_STICKY;
@Override
public void onDestroy()
super.onDestroy();
Toast.makeText(this,"ServiceDestroyed",Toast.LENGTH_LONG).show();
private int DownloadFile(URL url)
try
//---simulate taking sometime to download a file---
Thread.sleep(5000);
catch(InterruptedException e)
e.printStackTrace();
//---return an arbitrary number representing
//the size of the file downloaded---
return 100;
private class DoBackgroundTask extends AsyncTask<URL, Integer, Long>
protected Long doInBackground(URL... urls)
int count = urls.length;
long totalBytesDownloaded = 0;
for (int i = 0; i < count; i++)
totalBytesDownloaded += DownloadFile(urls[i]);
//---calculate percentage downloaded and
// report its progress---
publishProgress((int) (((i+1) / (float) count) * 100));
return totalBytesDownloaded;
protected void onProgressUpdate(Integer... progress)
Log.d("Downloading files", String.valueOf(progress[0]) + "% downloaded");
Toast.makeText(getBaseContext(), String.valueOf(progress[0]) + "% downloaded", Toast.LENGTH_LONG).show();
protected void onPostExecute(Long result)
Toast.makeText(getBaseContext(), "Downloaded " + result + " bytes", Toast.LENGTH_LONG).show();
stopSelf();
【讨论】:
我想发出一个 http 请求。以上是关于在服务中运行 AsyncTask - Android的主要内容,如果未能解决你的问题,请参考以下文章
OnCreate 中的 AsyncTask 在运行时失败,如何在 Android 中避免这种情况?