我正在设计一款Android应用程序,要求我让main Thread
睡眠一段时间,我知道这会让应用程序冻结, UI 将不是一个可编辑的材料,但是,这是我在我的应用程序中所需要的,我很好,问题是,当用户因此击中用户当main Thread
正在睡觉时,应用程序崩溃并向我提供以下Log
:
06-15 13:10:57.620: E/ActivityManager(542): ANR in com.example.myapp (com.example.myapp/.Login)
06-15 13:10:57.620: E/ActivityManager(542): PID: 1339
06-15 13:10:57.620: E/ActivityManager(542): Reason: Input dispatching timed out (Waiting because the touched window has not finished processing the input events that were previously delivered to it.)
06-15 13:10:57.620: E/ActivityManager(542): Load: 0.67 / 0.36 / 0.14
06-15 13:10:57.620: E/ActivityManager(542): CPU usage from 8638ms to 2834ms ago:
06-15 13:10:57.620: E/ActivityManager(542): 2.7% 112/mediaserver: 0.1% user + 2.5% kernel
06-15 13:10:57.620: E/ActivityManager(542): 1.2% 542/system_server: 0.6% user + 0.5% kernel / faults: 10 minor
06-15 13:10:57.620: E/ActivityManager(542): 1% 100/vinput: 0% user + 1% kernel
06-15 13:10:57.620: E/ActivityManager(542): 1% 1339/com.example.myapp: 0.8% user + 0.1% kernel / faults: 19 minor
06-15 13:10:57.620: E/ActivityManager(542): 0.5% 102/local_opengl: 0% user + 0.5% kernel
06-15 13:10:57.620: E/ActivityManager(542): 0.3% 109/surfaceflinger: 0.3% user + 0% kernel
06-15 13:10:57.620: E/ActivityManager(542): 0% 3/ksoftirqd/0: 0% user + 0% kernel
06-15 13:10:57.620: E/ActivityManager(542): 0.1% 56/adbd: 0% user + 0.1% kernel
06-15 13:10:57.620: E/ActivityManager(542): 0% 103/local_gps: 0% user + 0% kernel / faults: 4 minor
06-15 13:10:57.620: E/ActivityManager(542): 0.1% 598/com.android.systemui: 0.1% user + 0% kernel / faults: 1 minor
06-15 13:10:57.620: E/ActivityManager(542): 0% 697/com.android.inputmethod.latin: 0% user + 0% kernel / faults: 5 minor
06-15 13:10:57.620: E/ActivityManager(542): 4% TOTAL: 1.4% user + 2.5% kernel
06-15 13:10:57.620: E/ActivityManager(542): CPU usage from 696ms to 1199ms later:
06-15 13:10:57.620: E/ActivityManager(542): 1.7% 100/vinput: 0% user + 1.7% kernel
06-15 13:10:57.620: E/ActivityManager(542): 2% TOTAL: 2% user + 0% kernel
如何防止让我的应用在睡觉时忽略任何用户互动?
如果值得一提,我在InterruptedException
睡觉时抓住Thread
:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
答案 0 :(得分:3)
在相关小部件和操作栏项目上调用setEnabled(false)
,以防止他们接受用户输入。然后,在后台运行长时间运行的工作,例如通过AsyncTask
。工作完成后,请在相关小部件和操作栏项目上调用setEnabled(true)
,例如onPostExecute()
的{{1}}。
请注意,您需要处理配置更改,以便在用户在后台工作时旋转屏幕时重新禁用窗口小部件和操作栏项。
此外,请仅禁用与后台任务真正相关的小部件和操作栏项。不要阻止用户在应用程序中的其他位置导航到不依赖于此工作的位置(帮助屏幕,屏幕等)。
使用AsyncTask
而不是“请等待..文字视图”,或者除了“请等待..文字视图”之外,您也可以提供更好的服务。