Search code examples
androidjsonsendpingprogrammatically-created

Send Ping on Android programmatically


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!


Solution

  • 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!