我使用后台服务来执行CPU密集型任务。我希望能够在不中断服务的情况下从客户端活动中停止CPU密集型任务。
我已经定义了
public static AtomicBoolean isAborted = new AtomicBoolean(false);
以及客户端活动与ScCommon
类中的多个后台服务之间共享的其他几个变量/常量。
在客户活动中,我有以下代码
if (isSolveServiceBound) {
ScCommon.isAborted.set(true);
}
在后台服务的CPU密集型任务中,我测试并重置了这个atomicboolean:
if (ScCommon.isAborted.get()) {
undoAction(false, true);
ScCommon.isAborted.set(false);
return;
}
在CPU密集型任务启动后将atomicboolean设置为true
时,后者永远不会看到此更改的值。
我的实施有什么问题?
****编辑****
以下是来自主要"客户端"的更详细代码。活性:
public class ScMain extends AppCompatActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener {
Handler scMainHandler = new Handler();
. . .
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
. . .
scMainHandler.post(BackgroundInitialisation);
. . .
}
final Runnable BackgroundInitialisation = new Runnable() {
public void run() {
. . .
if (intentSolveService == null) {
intentSolveService = new Intent(mContext, ScSolveService.class);
}
if (!isSolveServiceBound) {
bindService(intentSolveService, solveServiceConnection, Context.BIND_AUTO_CREATE);
}
. . .
};
public void UndoBtnFired(View view) {
if (isSolveServiceBusy) {
if (isSolveServiceBound) {
ScCommon.isAborted.set(true);
}
resetContext(STEP, null);
return;
} else {
undoAction();
}
}
来自后台服务的更多代码:
public class ScSolveService extends Service {
. . .
public class IncomingHandler extends Handler {
@Override
public void handleMessage(Message message) {
isSolveServiceBusy = true;
msg = message;
msgArg1 = message.arg1;
msgWhat = message.what;
if (message.replyTo != null) {
mClient = new Messenger(message.replyTo.getBinder());
}
switch (msg.what) {
case MSG_SOLVE:case MSG_ANALYZE:case MSG_SUGGEST:case MSG_STEP:
solve();
ScCommon.isSolveServiceBusy = false;
break;
. . .
}
}
}
public void solve() {
. . .
LOOP:
do {
. . .
if ((keepWorking && (isNextStepRequested || isSuggestionRequested)) || isAborted.get()) {
break LOOP;
}
. . .
} while(isChanged);
if (isAborted.get()) {
undoAction(false, true);
isAborted.set(false);
return;
}
. . .
}
}