我想在用户关闭应用程序时清空服务器端的表以获取mac地址.因此,我从onDestroy()MainActivity中的方法启动IntentService类,但是没有启动Service .我已经在Manifest中注册了它.当我把代码放在onStop()服务中的onDestroy 启动时.
我不能在做这个工作onPause()或者onStop因为应用程序必须能够将数据记录(latitude, longitude, Speed, mac and time)在后台.
如果以这种方式不可能,我该如何管理它?
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);
Run Code Online (Sandbox Code Playgroud)
}
IntentService类:
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();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
表现:
<service android:name=".ClearTable" />
Run Code Online (Sandbox Code Playgroud)
不要尝试你的运气onDestroy(),这是非常不可靠的,因为它不能保证被调用,你应该决定其他的事情:
正如您在问题中所说:
我想在用户关闭应用程序时清空服务器端的 MAC 地址表。
那么为什么不重写onBackPressed()基本 Activity(Launching Activity) 的方法呢?并处理你的逻辑。
编辑
在OP关于做某事的评论之后,当用户在后台关闭应用程序时:不!没有可靠的方法来检查/检测您的应用程序何时在后台被杀死,无论是用户强制关闭还是系统决定杀死它,以防它需要恢复内存。
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |