gpt4 book ai didi

来自处理程序中运行的代码的 Android ANR?

转载 作者:行者123 更新时间:2023-11-29 16:10:57 25 4
gpt4 key购买 nike

我前段时间写的一个游戏有 ANR 问题,调试表明它们是 HTTP 请求花费很长时间(因此导致 ANR)。

我认为通过将 HTTP 代码分配到从处理程序中调用的 Runnable 中,我可以避免 ANR - 但似乎并非如此?

堆栈转储表明可运行/处理程序代码仍在“主”线程中运行,因此仍会导致 ANR??

它执行的任务是异步的(上传高分和成就),因此可以启动并完全留给它自己的设备 - 实现此任务的最佳方式是什么,这样 ANR 就不会成为问题?

一个主题建议 Handler 应该在 Application 类中创建,而不是在 Game 的 Activity 中创建 - 但我找不到关于这些情况之间差异的任何详细信息??

非常感谢所有想法。

附注将此扩展为询问 - 我假设与 HTTP 相关的 ANR 归结为电话服务中断/网络/WiFi,因为我为这些请求设置了 SHORT 超时(它们不是必需的,可以重试后来!?)

最佳答案

Handler 将在当前线程中默认执行代码/处理消息(任何没有 Looper 的构造函数,例如 new Handler())。在几乎所有情况下,这都是主线程。如果你想让它在不同的线程中执行,你必须告诉它应该使用哪个 Looper 线程。

Android 有一个名为 HandlerThread 的实用程序类,它创建一个带有 LooperThread

简短示例:

public class MyActivity extends Activity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HandlerThread handlerThread = new HandlerThread("background-handler");
handlerThread.start();
Looper looper = handlerThread.getLooper();
mHandler = new Handler(looper);

mHandler.post(new Runnable() {
public void run() {
// code executed in handlerThread
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// stops the HandlerThread
mHandler.getLooper().quit();
}
}

如果您的任务只需要一些信息并且不需要返返回告,我会使用 IntentService。如果您的 Activity-lifecycle 重新创建 Activity,这些不会发疯。

你会在它自己的文件中创建一个小的Service

public class SaveService extends IntentService {
public SaveService() {
super("SaveService");
}
@Override
protected void onHandleIntent(Intent intent) {
if ("com.example.action.SAVE".equals(intent.getAction())) {
String player = intent.getStringExtra("com.example.player");
int score = intent.getIntExtra("com.example.score", -1);
magicHttpSave(player, score); // assuming there is an implementation here
}
}
}

将其添加到 AndroidManifest.xml

<application ....

<service android:name=".SaveService" />
</application>

在你的代码中开始

Intent intent = new Intent(this /* context */, SaveService.class);
intent.setAction("com.example.action.SAVE");
intent.putExtra("com.example.player", "John123");
intent.putExtra("com.example.score", 5123);
startService(intent);

IntentService#onHandleIntent() 已经在后台线程上运行,因此您不必为此操心。

关于来自处理程序中运行的代码的 Android ANR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368762/

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