简体   繁体   English

以编程方式在Android上发送Ping

[英]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 ?? 我需要将JSON格式的Ping发送到服务器,我已经将其包含所有需要的信息...时间戳,位置,device_id等...但是..如何每5分钟发送一次自动?? 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! 非常感谢!

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. 如果要执行一些定期重复的任务,建议您使用Android SDK的AlarmManager组件。警报管理器是一项系统服务,因此您可以使用以下代码行进行访问。

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

You will then receive the alarm in an AlarmReceiver. 然后,您将在AlarmReceiver中接收警报。

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. AlarmReciever类扩展了BroadcastReceiver并覆盖onRecieve()方法。 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. 在onReceive()中,您可以根据需要启动活动或服务,例如可以启动活动以振动电话或拨打电话。

Here is an article from Android Developers that describes how to use AlarmManager and AlarmReceiver : http://developer.android.com/training/scheduling/alarms.html . 这是来自Android开发人员的文章,描述了如何使用AlarmManager和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. 成功使用AlarmManager设置警报(每5分钟)并将其拦截到AlarmReceiver中之后,可以启动IntentService,它将ping json发送到您的服务器。

I hope this helps. 我希望这有帮助。 Cheers! 干杯!

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. 如果您想在修复时间后从android应用中命中服务器,则应创建一个后台服务。此服务类会在特定的延迟下频繁调用服务器。

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. 每隔5分钟它将对您的服务器执行一次ping操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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