0

Ok, I have no Idea how to do this, I need some help.

I need to send a Ping in JSON format into a server, I've already have it with all the information that I need... timestamp, location, device_id, etc... But.. how can I send it each 5 minutes automatically ?? I'm still looking for something useful but I have no succes.. I'm kind of new on this..

here's an example of my code, feel free to use it if it is useful for you :) ...

package com.example.hugo.ping03;

// imports....

public class MainActivity extends ActionBarActivity {
//HTTP
private AsyncHttpClient client;//crear cliente
private AsyncHttpResponseHandler handler;//crear handler

private Button send;

//JSON
JSONObject json; //objeto json
Context context = this; //context element
private StringEntity entity; //entity

//Battery
private IntentFilter batIntentFilter;
private Intent battery;
private int nivelBateria;

//device_id
private String id;

//timestamp
private int time;
private Timestamp tsTemp;
private Long tsLong;
private String ts;

//GPS (this one comes from another class.java)
GPSTracker gps;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ping03);

    client = new AsyncHttpClient();

    String password = "pass";
    client.setBasicAuth("hugo", password);
    send  = (Button) findViewById(R.id.send);
    //battery level:
    batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    battery = this.registerReceiver(null, batIntentFilter);
    nivelBateria = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    //device_id:
    id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    //timestamp
    time = (int) (System.currentTimeMillis());
    tsTemp = new Timestamp(time);
    tsLong = System.currentTimeMillis()/1000;
    ts =  tsLong.toString();

    handler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
            Log.d("onSuccess","ping exitoso !!!!");
            Log.d("Nivel de Bateria:",String.valueOf(nivelBateria));
            Log.d("Id de Dispositivo",id);
            Log.d("Timesatmp:",ts);
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)

            String statuscode = String.valueOf(statusCode);
            Log.d("onFailure","ping nulo a causa de: ");
            Log.d("Server statusCode",statuscode);
        }
    };

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //mensaje a Log para indicar clic en botón
            Log.d("onPressButton","Click exitoso");
            String klientourl = "server url";

            //Strings to Post JSON :
            String status = "1";
            String device_id = id;
            String timestamp =ts;
            String battery = String.valueOf(nivelBateria);
            json = new JSONObject();
            gps = new GPSTracker(Ping03.this);//creamos objeto de clase
            //if GPS is Enabled... 
            if (gps.canGetLocation()){
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                Log.d("Location is:", "Lat: "+latitude+" Long: "+longitude);
                String IamHere = "Lat: "+latitude+" Long: "+longitude;

            try {
                json.put("geo", IamHere);
                json.put("status", status);
                json.put("device_id", device_id);
                json.put("timeStamp", timestamp);
                json.put("battery", battery);
            }catch (JSONException e){
                Log.e("Json", "unexpected JSON exception", e);
            }
            try {
                entity = new StringEntity(json.toString());
                entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                client.post(context, klientourl, entity, "application/json", handler);
            }catch (Exception e){}
            }else {
                //if we can
                gps.showSettingsAlert();
                Log.d("Geoloc: ", "Disabled?");
            }
        }// ./ end onClick
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_ping03, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
} }

Any ideas? thanks a lot!

HGRC
  • 577
  • 1
  • 5
  • 7

2 Answers2

1

If you want to perform some periodically repeating tasks, I'd suggest you make use of a AlarmManager component of the Android SDK.Alarm manager is a system service, thus you can access it by using the following line of code.

    AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().

You will then receive the alarm in an AlarmReceiver.

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone.

Here is an article from Android Developers that describes how to use AlarmManager and AlarmReceiver : http://developer.android.com/training/scheduling/alarms.html. After you are successful of setting an alarm with AlarmManager (for every 5 minutes) and intercepting it in your AlarmReceiver, you can start an IntentService that will send the ping json to your server.

I hope this helps. Cheers!

jonDoe
  • 268
  • 1
  • 12
  • Thanx ! it was the very best choice, cause i needed it even when the app goes to sleep. – HGRC Mar 05 '15 at 20:05
1

If you want to hit you server from android app after a fix time you should create a background service.and this service class will call server on a specific delay frequently.

public class MyService extends Service{

    Handler mHandler = new Handler();

    @Override
    public IBinder onBind(Intent arg0){
       return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
       Log.e(TAG, "onStartCommand");
       super.onStartCommand(intent, flags, startId);       
       return START_STICKY;
    } 

    @Override
    public void onCreate(){
       Log.e(TAG, "onCreate");
       mHandler.postDelayed(mRun,300000);
    }

    Runnable mRun = new Runnable() {

       @Override
       public void run() {
           // TODO call your service here
           mHandler.postDelayed(mRun,300000);

       }
    };

}

start service from your activity like below -

private void startService(){
    Handler mStartServicehandler = new Handler();
    mStartServicehandler.post(new Runnable() {
        @Override
        public void run() {
            startService(new Intent(mContext,MyService.class));
        }
    });
}

do something like this. It will ping your server after every 5 min.

Ravi Bhandari
  • 4,682
  • 8
  • 40
  • 68
  • 1
    I have found that postDelayed() is very flaky when dealing with larger time intervals. At my work we used to use postDelayed() for lots of things, but we then realized that if the device goes to sleep, the time interval can be very unpredictable. A 5 minute interval can turn into a much longer interval in that case. We have switched to using AlarmManagers for longer intervals. Take a look at this link: http://binarybuffer.com/2012/07/executing-scheduled-periodic-tasks-in-android – Daniel Nugent Mar 03 '15 at 05:05