简体   繁体   中英

Get data from internet every x minutes

I creating the phone tracking app, i want to get the data from the internet (actualy the latitude and longitude) from the device i tracked. the tracked phone is okay, they send the latitude and longitude every onLocationChanged executed to my database server. And for the tracking phone app i can get that data but just when oncreate once. i get the data using asynctask, The problem is i having difficluties to get that data every X minutes, should i use handler ? can somebody here help me with some code ?

Here is my code so far

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String Url = "http://mysite.com/tes.php";

    mf =(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
    gmap = mf.getMap();
    gmap.setMyLocationEnabled(true);
    gmap.setMapType(gmap.MAP_TYPE_SATELLITE);

    lat= (TextView) findViewById(R.id.lati);
    longit = (TextView) findViewById(R.id.longi);



            // TODO Auto-generated method stub
             lokasibaru lokasi = new lokasibaru();
            lokasi.execute(Url);


}

and this is my asynctask

private class lokasibaru extends AsyncTask <String,ArrayList<String>,ArrayList<String>>{

    String latitude,longitude;      

        protected void onProgressUpdate(String... values) {


            }
        protected void onPostExecute(ArrayList<String> hasil) {

        latitude = hasil.get(0);
        longitude = hasil.get(1);
        lat.setText(latitude);  
        longit.setText(longitude);


        }

        @Override
        protected ArrayList<String> doInBackground(String... value) {
            ArrayList<String> result = null ;
            String Url = value[0];
            koneksi get = new koneksi();

            try {
                //result = GetR.getdata(Url);
                result = get.getdata(Url);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            return result;
        }

    }

and this is my koneksi class to get the data from internet

public class koneksi {

public ArrayList<String> getdata(String url) throws Exception{
    BufferedReader in = null;
    String data = null;
    ArrayList<String> kordinat = new ArrayList<String> ();
    int count ;
    try{
        HttpClient client= new DefaultHttpClient();
        URI site = new URI(url);
        HttpGet req = new HttpGet();
        req.setURI(site);
        HttpResponse resp = client.execute(req);
        count =0;
        in = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");

        while ((l = in.readLine()) != null ){
        //sb.append(l+nl);
        kordinat.add(l);
        count++;
        }
    in.close();
    data = sb.toString();
    return kordinat;
    }
    finally{

    }

}

}

Use a handler

   private Handler m_handler = new Handler();

// ..............

Runnable m_handlerTask = new Runnable() {

    @Override
    public void run() {
        m_handler.postDelayed(m_handlerTask, Xmins);
             new lokasibaru().execute();
    }
};


private void startGettingDataTask()
{
    m_handlerTask.run(); 
}

private void stopGettingDataTask()
{
    m_handler.removeCallbacks(m_handlerTask);
}

Call startGettingDataTask() to start and stopGettingDataTask() to remove the callbacks!

Look into Android Service , within the service create a ScheduledExecutorService which starts a Runnable task that request the page and sends the location.

To the ScheduledExecutorService you can pass the time interval like so,

//this will run the task every 5 minutes
scheduleTaskExecutor.scheduleAtFixedRate(task, 0, 5, TimeUnit.MINUTES);

For below API 9

//this will run the task every 5 minutes
scheduleTaskExecutor.scheduleAtFixedRate(task, 0, 300, TimeUnit.SECONDS);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM