在服务中运行AsyncTask - Android

问题描述 投票:0回答:1

我试图在Android服务中使用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();
        }
    }
}

}

android service android-asynctask
1个回答
0
投票

看看这段代码可能有用..

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, "Service​Started",​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,​"Service​Destroyed",​Toast.LENGTH_LONG).show(); ​​
​    } ​​​​

    ​​​​private ​int ​DownloadFile(URL​ url) {
        ​try ​{    
    ​​​​​​​​​​​​        //---simulate​ taking ​some​time ​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();
    ​​​​​​​​    } 
​​​    }
}
© www.soinside.com 2019 - 2024. All rights reserved.