我试图每分钟检查2个字符串的值,然后关闭线程 当值不同时,这段代码会冻结我的UI。这就是代码。
@Override
protected void onPostExecute(String result)
{
//Download sourcecode on String
String secondaChar = result;
//Strings declaration
String First = "";
String Second = "";
try
{
//Writing sourcecode on string
Write(secondaChar);
String ReadingFile="FileSorgente";
First=reading(ReadingFile);
while (true)
{
// Downloading new sourcecode on string
secondaChar = result.replaceAll("[^a-zA-Z]+", "");
//writing new SC on string
Scrittura(secondaChar);
// new SC on second string
Second = Reading(ReadingFile);
// check until 2 strings are the same
if(First.equalsIgnoreCase(Second))
{
Toast.makeText(getApplicationContext(), "Keep Checking", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "FALSE", Toast.LENGTH_LONG).show();
break;
}
Thread.sleep(60 * 1000);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
textView.setText("Usless");
}
阅读和写作是两种不同的方法,我在java中测试它并且它有效,但可能在Android sdk中我必须做一些不同的事情。
答案 0 :(得分:1)
您应该在Thread.sleep(...)
中执行长时间运行的任务 - 例如,doInBackground()
- 这是在UI线程上运行的。
onPostExecute()
应该仅在doInBackground()
完成后调用,并且完全用于更新UI - 因此它在UI线程上运行。您在此处的每次延迟都会导致您的应用无响应。
要解决此问题,请将您的逻辑移至doInBackground()
。记住,所有UI操作都必须在UI线程上进行。因此,例如,显示祝酒词必须从onPostExecute()
或onProgressUpdate()
完成。
有关如何执行此操作的示例,请参阅this excellent answer。请注意,Thread.sleep()
也会调用doInBackground()
。
答案 1 :(得分:0)
@Override
protected void doInBackground(params....)
{
//Download sourcecode on String
String secondaChar = result;
//Strings declaration
String First = "";
String Second = "";
try
{
//Writing sourcecode on string
Write(secondaChar);
String ReadingFile="FileSorgente";
First=reading(ReadingFile);
while (true)
{
// Downloading new sourcecode on string
secondaChar = result.replaceAll("[^a-zA-Z]+", "");
//writing new SC on string
Scrittura(secondaChar);
// new SC on second string
Second = Reading(ReadingFile);
// check until 2 strings are the same
if(First.equalsIgnoreCase(Second))
{
publishProgress( "Keep Checking" );
}
else
{
publishProgress( "FALSE" );
break;
}
Thread.sleep(60 * 1000);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
publishProgress("Usless");
}
@Override
protected void onProgressUpdate(String... progress) {
showToast(progress[0]);
}