问题描述:

What happens if a child thread's call back method existed in an Activity that was destroyed or that is now NOT the Activity at the top of the stack?

WIll this cause and exception? if so, what is the best practice to deal with this kind of issue? Thanks!

网友答案:

You should make your thread work like this:

class Job extends Thread {
    Activity activity;
    boolean needsFinishing;

    Job(Activity activity) {
        this.activity = activity;
    }

    synchronized void detachActivity() {
        activity = null;
    }

    synchronized void attachActivity(Activity activity) {
        this.activity = activity;
        if (needsFinishing) {
            finished();
        }
    }

    public void run() {
        // do long running job

        finished();
    }

    synchronized void finished() {
        if (activity != null) {
            needsFinishing = false;
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    // do your stuff with the activity
                }
            });
        } else {
            needsFinishing = true;
        }
    }
}

And the Activity:

class MyActivity extends Activity {
    Job job;

    void onCreate(Bundle bundle) {
        job = (Job) getNonConfigurationInstance();
    }

    void onResume() {
        if (job != null) {
            job.attachActivity(this);
        }
    }

    void onPause() {
        if (job != null) {
            job.detachActivity();
        }
    }

    Object onRetainNonConfigurationInstance() {
        return job;
    }

    // create and start your job somewhere between onCreate and onPause
}

This will make sure the thread only accesses the activity when appropriate. It will handle orientation changes, too. Note, the code is not perfect as I don't have a java/android environment handy to check for errors.

网友答案:

You can use Future class to if you want to monitor when the task is completed.

Other alternative is to post tasks in a Handler and if you just want to stop them to use RemoveCallback(Runnable r)

网友答案:

you can also maintain you that code snippet in a centric class which is a non-activity and a simple .java class

相关阅读:
Top