我正用这个撕掉我的头发!我是Android的新手,所以我确信这是非常明显的。
我在ScheduledThreadPoolExecutor
cause: null
例外
我想要的只是一个单独的线程,只要活动在屏幕上就会运行!
// Instance Variables
private ScheduledExecutorService m_oScheduledExecutor = null;
@Override
protected void onResume()
{
super.onResume();
if (oScheduledExecutor == null)
{
oScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
}
try
{
oScheduledExecutor.scheduleAtFixedRate({Runnable Instance HERE}, 0, 10, TimeUnit.SECONDS);
}
catch (Exception e)
{
System.out.println("(MainActivity) Error: " + e.getMessage() + " Cause: " + e.getCause());
}
}
@Override
protected void onStop()
{
super.onStop();
m_oScheduledExecutor.shutdown();
}
编辑:整个堆栈跟踪....
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@41976688 rejected from java.util.concurrent.ScheduledThreadPoolExecutor@4195c7f8[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1979)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:786)
at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute(ScheduledThreadPoolExecutor.java:300)
at java.util.concurrent.ScheduledThreadPoolExecutor.scheduleAtFixedRate(ScheduledThreadPoolExecutor.java:545)
at java.util.concurrent.Executors$DelegatedScheduledExecutorService.scheduleAtFixedRate(Executors.java:619)
at com.example.wifitest.MainActivity.onResume(MainActivity.java:61)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
at android.app.Activity.performResume(Activity.java:5182)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:8)
您不能'回收'ExecutorService
。调用shutdown()
后,尝试安排任何任务都会导致拒绝,在您的情况下,拒绝政策会抛出RejectedExecutionException
。
如果您关注堆栈跟踪,则可以在ScheduledThreadPoolExecutor
中看到:
/**
* Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
*/
private void delayedExecute(Runnable command) {
if (isShutdown()) {
reject(command);
return;
}
// ...
}
将执行程序服务作为实例变量保存在这里对你不起作用:一旦它被关闭,它就不能再次使用了。
答案 1 :(得分:0)
不要在onStop()方法中关闭ScheduledExecutorService。尝试将其放在onDestroy()方法中。当您的活动进入后台时,可能会调用onStop()方法,因为您的活动在后台不可见。因此,如果ScheduledExecutorService关闭,您可能会收到此错误。