In Android, is it safe to call Activity.finish()
from a background thread, or can it only called from the main thread? The documentation doesn't mention anything about thread safety of this method.
Choosing between a service and a thread A service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.
Background processing in Android refers to the execution of tasks in different threads than the Main Thread, also known as UI Thread, where views are inflated and where the user interacts with our app.
If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.
Processor with 2 core will handle 2 threads at a time( concurrent execution of two threads). Processor with 4 core will handle 4 threads at a time( concurrent execution of four threads. For IO bound operations running more threads than cores is still beneficial because most of them can do the waiting in parallel.
No, it is not.
The code uses at least one variable, mFinished, without synchronization. Full stop.
public void finish() {
if (mParent == null) {
int resultCode;
Intent resultData;
synchronized (this) {
resultCode = mResultCode;
resultData = mResultData;
}
if (false) Log.v(TAG, "Finishing self: token=" + mToken);
try {
if (resultData != null) {
resultData.setAllowFds(false);
}
if (ActivityManagerNative.getDefault()
.finishActivity(mToken, resultCode, resultData)) {
mFinished = true;
}
} catch (RemoteException e) {
// Empty
}
} else {
mParent.finishFromChild(this);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With