当用户关闭应用程序时,我希望在服务器端清空与MAC地址相关的表格。因此,我从MainActivity中的onDestroy()方法启动IntentService类,但服务未能启动。我已经在Manifest中注册了它。当我将代码放在onStop()中时,服务就会启动。
由于应用程序必须能够在后台记录数据(纬度、经度、速度、MAC和时间),因此我无法在onPause()或onStop()中完成此任务。
如果无法使用这种方式,我该如何处理?
MainActivity中的onDestroy():
由于应用程序必须能够在后台记录数据(纬度、经度、速度、MAC和时间),因此我无法在onPause()或onStop()中完成此任务。
如果无法使用这种方式,我该如何处理?
MainActivity中的onDestroy():
@Override
protected void onDestroy() {
super.onDestroy();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("mac", macAddress);
System.out.println("JsonObject" + jsonObject);
String json = jsonObject.toString();
Intent intent2 = new Intent(MainActivity.this,
ClearTable.class);
intent2.putExtra("json_mac", json);
startService(intent2);
}
IntentService class:
public class ClearTable extends IntentService{
public ClearTable() {
super("IntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
BufferedReader reader = null;
try {
String jSONString = intent.getStringExtra("json_mac");
System.out.println("xyz The output of : doInBackground "
+ jSONString);
URL myUrl = new URL(
"https://serverside-apple.rhcloud.com/webapi/test");
HttpURLConnection conn = (HttpURLConnection) myUrl
.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
// write to the output stream from the string
wr.writeBytes(jSONString);
wr.close();
System.out.println("xyz The output of getResponsecode: "
+ conn.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
清单文件:
<service android:name=".ClearTable" />
onDestroy()
方法不保证一定会被调用,因此在其中放置重要的代码是危险的。 - Sharp Edge