开发者

Activity spawns a thread, but then the activity gets destroyed or an new activity (in the same task) gets created before child thread finishes

开发者 https://www.devze.com 2023-02-12 06:04 出处:网络
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?

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, w开发者_运维技巧hat is the best practice to deal with this kind of issue? Thanks!


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 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 also maintain you that code snippet in a centric class which is a non-activity and a simple .java class

0

精彩评论

暂无评论...
验证码 换一张
取 消