Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to finish an android activity from a background thread?

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.

like image 826
Heath Borders Avatar asked Dec 05 '13 23:12

Heath Borders


People also ask

Does Android service run in background thread?

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.

What is background thread in Android?

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.

Why should you avoid to run non UI code on the main thread?

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.

How many threads can be executed at a time in Android?

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.


1 Answers

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);
    }
}
like image 97
G. Blake Meike Avatar answered Nov 16 '22 01:11

G. Blake Meike