无限期地运营服务

时间:2015-07-29 17:30:09

标签: android service android-asynctask background

我正在创建一个始终从服务器发送和接收数据的应用程序。我需要它尽快更新数据,因为每一秒都在改变在线数据。我创建了这个类,但它不起作用,一次挂起。想知道这是否"而(真实)"是无限期运行函数的正确方法,因为它找不到更像

的东西
    package nilson.online; /**
* Created by nilso_000 on 23/07/2015.
*/
import android.app.Service;
    import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;

import nilson.BancoDados;
//this class contains a basic instructions to open a web page and send a POST form
import static nilson.online.ServiceOnline.executaHttpPost;

public class ServiceFilaOnlineB extends Service {

String metodo="";
String url="";
ArrayList<NameValuePair> parametrosPost;

public SQLiteDatabase banco = null;
private BancoDados gerenciaBanco;

public ServiceFilaOnlineB(){}

@Override
public void onCreate() {
    Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}

@Override
public void onStart(Intent intent, int startId) {
    try {
        banco = openOrCreateDatabase("LNM", MODE_MULTI_PROCESS, null);
        gerenciaBanco = new BancoDados();
        gerenciaBanco.abrirBD(banco);
    }catch (Exception e){
        Log.e("LNM erro servico1", "error to init the service " + e);
        onDestroy();
    }try {
        //Here I create the loop that will run indefinitely in android
        //even to restart the system. It has two functions:
        //1-check for updates offline and send then to the server online
        //2-chec for updates online and copy then to the SQLite offline
        while(true) {
            //This is the records of updates offline
            Cursor c = gerenciaBanco.getFilaOnline();
            if (c.moveToFirst()) {
                url = "http://192.168.10.100/lnm/add.php";
                metodo = "POST";
                Log.e("LNM Fila", "Size of fila: " + c.getCount());
                do {
                    parametrosPost = new ArrayList<>();
                    parametrosPost.add(new BasicNameValuePair("SQL", c.getString(0)));

                    new InsertDataTask().execute(parametrosPost);
                    new GetDataTask().execute(parametrosPost);
                } while (c.moveToNext());
            }
            Thread.sleep(5 * 1000);
        }
    }catch (Exception e){
        Log.e("LNM erro servico2", "error to init the service " + e);
        onDestroy();
    }
}
private class InsertDataTask extends AsyncTask<ArrayList<NameValuePair>, String, String> {

    protected void onPostExecute(String result){
        Log.e("LNM Resultado", "Command executed "+result);
        result = result.replaceAll("\\s+"," ").trim();
        Log.e("LNM", "" + result.substring(0,6));

        if("INSERT".equals(result.substring(0,6))) {
            String res[]=result.split("\\|");
            Log.e("LNM Comando Online", "The record was inserted int the db ONLINE and returned the ID " + res[1]);
        }else
            Log.e("LNM Conexao realizada", "Error " + result);
    }

    private String executa(ArrayList<NameValuePair>... params){
        String result;
        try {
            result = executaHttpPost(url, params[0]);
            Log.d("LNM Conectado"," Command executed "+result);
            return result;
        } catch (Exception e) {
            Log.d("LNM Error on POST",""+e);
            return  executa(params);
        }
    }

    @Override
    protected String doInBackground(ArrayList<NameValuePair>... params) {
        return executa(params);
    }
}
private class GetDataTask extends AsyncTask<ArrayList<NameValuePair>, String, String> {

    protected void onPostExecute(String result){
        Log.e("LNM Resultado", "Command executed "+result);
        result = result.replaceAll("\\s+"," ").trim();
        Log.e("LNM", "" + result.substring(0,6));
        //Separate results by | and insert in db
        if("SUCESS".equals(result.substring(0,6))) {
            String res[]=result.split("\\|");
            Log.e("LNM Comando Online", "Data updated " + res[1]);
            //Updating the record OFFLINE with the ID ONLINE
            gerenciaBanco.updateMatch("online", res);
        }else
            Log.e("LNM Conexao realizada", "Error " + result);
    }

    private String executa(ArrayList<NameValuePair>... params){
        String result;
        try {
            result = executaHttpPost(url, params[0]);
            Log.d("LNM Conectado"," Command executed "+result);
            return result;
        } catch (Exception e) {
            Log.d("LNM Error on POST",""+e);
            return  executa(params);
        }
    }

    @Override
    protected String doInBackground(ArrayList<NameValuePair>... params) {
        return executa(params);
    }
}

@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
}

}

0 个答案:

没有答案