定期发送数据到服务器 [英] Periodically send data to server
问题描述
我正在开发一个通过蓝牙从Arduino接收数据并将其发送到服务器的应用程序。我已经完成了这部分的工作-用户按下按钮后,我将启动BT连接,接收数据并通过异步任务将其发送到服务器:
I'm working on an app that receives data from Arduino through Bluetooth and sends that data to server. I've got this part working - once a user presses a button, I initiate BT connection, receive data and send it to server via Async Task:
-
用于接收数据的线程:
Thread for receiving data:
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i("test", "Connected thread RUN");
byte[] buffer = new byte[256];
int bytes;
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
Log.i("test", "Trying....");
bytes = mmInStream.read(buffer);
handler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
ConnectedThread处理程序(接收数据,启动AsyncTask):
ConnectedThread handler (receives data, starts AsyncTask):
private final Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
//String readMessage = new String(readBuf, 0, msg.arg1);
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
Log.i("test", "sbprint: " + sbprint);
sendDataToServer(sbprint);
txtData.setText("Data from Arduino: " + sbprint);
}
break;
}
};
};
sendDataToServer方法:
sendDataToServer method:
private void sendDataToServer(String dataToSend){
if(dataToSend != null && !dataToSend.equals("")) {
sendDataAsyncTask = new SendDataAsyncTask(MyActivity.this, dataToSend);
sendDataAsyncTask.setSendDataListener(MyActivity.this);
sendDataAsyncTask.execute();
}
}
这或多或少有效。但是,现在我需要每两分钟重复一次该过程。我已经使用TimerTask了,但是当设备进入睡眠状态时,任务当然会停止运行。
This, more or less works. However, now I need to repeat the process every two minutes. I've got it working with TimerTask, but of course the task stops running when device goes to sleep.
我猜我需要一个服务和/或一个AlarmManager每两分钟唤醒一次设备并运行上面的代码?有什么提示吗?
I'm guessing I need a Service and / or an AlarmManager to wake the device every two minutes and run the above code? Any tips for this?
推荐答案
是的,没错。您需要实现 Service
来执行后台工作,即即使您的应用程序不在前台或设备显示关闭,也要向服务器发送数据。
Yes, that's right. You need to implement a Service
to do the background job, that is to execute sending data to server, even when your app is not on foreground or device display turning off.
您可以在此处使用我的示例代码之一: https://xjaphx.wordpress.com/2012/07/07/create-a-service-that-does-a-schedule-task/
You can use one of my example code here: https://xjaphx.wordpress.com/2012/07/07/create-a-service-that-does-a-schedule-task/
此外,如果要使 Service
处于最佳状态(即,使确保它没有被系统杀死),您需要通过以下方式对其进行频繁检查:
Additionally, if you want to make the Service
running in the best condition (that is, make sure it is not killed by system), you need to check it frequently by
-
实施
BOOT_RECEIVED
Intent
(BroadcastReceiver
),用于在设备启动时启动您的应用。
Implement a
BOOT_RECEIVED
Intent
, aBroadcastReceiver
, to launch your app when device is started.
注册 AlarmManager
以计划是否检查服务
是否在运行;如果它已经死了,则可以重新启动(唤醒)。
Register for an AlarmManager
to schedule check whether the Service
is running or not; if it dies already, you can re-start (wake) it up.
这篇关于定期发送数据到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!