我有一个执行 HTTP post 的方法...
当用户在此过程中旋转设备时,会导致 ANR。
这是我的代码...
public void uploadTransactions(View v)
{
final ProgressDialog prog;
try
{
// disable screen rotation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
// setup progress dialog
prog = new ProgressDialog(this);
prog.setTitle("Uploading Transactions");
prog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
prog.setIcon(R.drawable.appicon);
prog.setCanceledOnTouchOutside(false);
prog.setCancelable(false);
prog.show();
// setup thread for the sync
Thread syncThread = new Thread();
syncThread = new Thread()
{
public void run()
{
String result = "";
String currentFileContents = "";
GetByREST gbr = new GetByREST();
String URL = //url for ReST service
String URLparam = "";
String accountNo = //authorisation info
String emailAddress = //authorisation info
String password = //authorisation info
try
{
// loop through the files
File file = new File(SALES_DIRECTORY);
for (File thisFile : file.listFiles())
{
currentFileContents = readTransactions(thisFile);
updateProgress(prog, "Uploading " + thisFile.getName());
result = gbr.getRestOutput(URL, URLparam, accountNo, emailAddress, password, "3", new StringEntity(currentFileContents));
}
prog.dismiss();//dismiss the dialog
// ...re-enable rotation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
catch (Exception e)
{
messageBox("uploadTransactions: syncThread", e.getMessage());
}
}
};
syncThread.start();
}
catch (Exception e)
{
messageBox("uploadTransactions", e.getMessage());
}
}
如果屏幕为纵向,则效果很好,但在横向时,方向会返回到纵向并导致 ANR。我该如何解决这个问题?
最佳答案
问题是您可能(需要更多代码才能看到..)在您的 Activity 中将其作为随机方法。
您的 Activity 会因方向改变而重新开始。 不仅如此,当用户现在关闭您的应用程序时,您无法确定上传是否继续。
相反,您想要启动一个不绑定(bind)到 Activity 生命周期的服务。 这方面有足够的教程,现在您知道要寻找什么了。 您还可以尝试一下 RoboSpice 库,它正是这样做的。
ps。使用 AsyncTask 并不能解决这个问题,AsyncTask 本身仍然会绑定(bind)到您的 Activity 的生命周期。
关于java - 如何在执行 HTTP post 时处理屏幕旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18011980/