gpt4 book ai didi

android - 从 onDestroy 调用 IntentService

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:03:46 24 4
gpt4 key购买 nike

我想在用户关闭应用程序时清空服务器端的 mac 地址表。因此,我从 MainActivity 中的 onDestroy() 方法启动 IntentService 类,但服务启动。我已经在 list 中注册了它。当我将代码放入 onStop() 中的 onDestroy 时,服务启动。

我无法在 onPause()onStop 中完成这项工作,因为应用程序必须能够记录数据 (纬度、经度、速度、mac 和时间) 在后台。

如果这样不行,我该如何管理呢?

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 类:

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();
}
}
}

}

}

list :

 <service android:name=".ClearTable" />

最佳答案

与其使用 onDestroy() 试试运气,这是非常不可靠的,因为它不能保证被调用,您应该决定其他事情:

正如您在问题中所述:

I want to empty the table on the server side for a mac address when the user closes the application.

那么为什么不重写基础 Activity(Launching Activity) 的 onBackPressed() 方法呢?并在他们中处理您的逻辑。

编辑

在 OP 关于做某事的评论之后,当用户在后台关闭应用程序时:不!!没有可靠的方法来检查/检测您的应用程序何时在后台被终止,无论是用户强行关闭还是系统决定终止它,以防它需要恢复内存。

关于android - 从 onDestroy 调用 IntentService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32203957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com