以编程方式在 Android 上发送 Ping
Send Ping on Android programmatically
好的,我不知道该怎么做,我需要一些帮助。
我需要将 JSON 格式的 Ping 发送到服务器,我已经有了它以及我需要的所有信息...时间戳、位置、device_id 等。 .. 但是.. 我怎样才能每 5 分钟自动发送一次??我仍在寻找有用的东西,但我没有成功..我在这方面有点新..
这是我的代码示例,如果对您有用,请随时使用它:) ...
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);
} }
有什么想法吗?非常感谢!
如果你想执行一些周期性重复的任务,我建议你使用Android的AlarmManager组件 SDK.Alarm管理器是一个系统服务,因此你可以通过使用以下代码行。
AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().
然后您将在 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.
这是一篇来自 Android 开发人员的文章,描述了如何使用 AlarmManager 和 AlarmReceiver:http://developer.android.com/training/scheduling/alarms.html。使用 AlarmManager(每 5 分钟一次)成功设置警报并在 AlarmReceiver 中拦截它后,您可以启动一个 IntentService,它将 ping json 发送到您的服务器。
希望对您有所帮助。干杯!
如果你想在固定时间后从 android 应用访问你的服务器,你应该创建一个后台 service.and 此服务 class 将在特定延迟时频繁调用服务器。
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);
}
};
}
从您的 activity 启动服务,如下所示 -
private void startService(){
Handler mStartServicehandler = new Handler();
mStartServicehandler.post(new Runnable() {
@Override
public void run() {
startService(new Intent(mContext,MyService.class));
}
});
}
做这样的事情。
它会每隔 5 分钟对您的服务器执行一次 ping 操作。
好的,我不知道该怎么做,我需要一些帮助。
我需要将 JSON 格式的 Ping 发送到服务器,我已经有了它以及我需要的所有信息...时间戳、位置、device_id 等。 .. 但是.. 我怎样才能每 5 分钟自动发送一次??我仍在寻找有用的东西,但我没有成功..我在这方面有点新..
这是我的代码示例,如果对您有用,请随时使用它:) ...
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); } }
有什么想法吗?非常感谢!
如果你想执行一些周期性重复的任务,我建议你使用Android的AlarmManager组件 SDK.Alarm管理器是一个系统服务,因此你可以通过使用以下代码行。
AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().
然后您将在 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.
这是一篇来自 Android 开发人员的文章,描述了如何使用 AlarmManager 和 AlarmReceiver:http://developer.android.com/training/scheduling/alarms.html。使用 AlarmManager(每 5 分钟一次)成功设置警报并在 AlarmReceiver 中拦截它后,您可以启动一个 IntentService,它将 ping json 发送到您的服务器。
希望对您有所帮助。干杯!
如果你想在固定时间后从 android 应用访问你的服务器,你应该创建一个后台 service.and 此服务 class 将在特定延迟时频繁调用服务器。
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);
}
};
}
从您的 activity 启动服务,如下所示 -
private void startService(){
Handler mStartServicehandler = new Handler();
mStartServicehandler.post(new Runnable() {
@Override
public void run() {
startService(new Intent(mContext,MyService.class));
}
});
}
做这样的事情。 它会每隔 5 分钟对您的服务器执行一次 ping 操作。