iamxxyu 2015-10-13 09:00 采纳率: 0%
浏览 2665

Activity在回调函数执行前被finish会引起崩溃吗?

假设有如下情景,activity实现了接口interface A,override了操作函数function( )(是对activity里面的一些变量进行处理),activity里面开了两个线程(Thread1,Thread2)进行网络访问,Thread2中网络访问有响应后执行了回调函数function,而Thread1网络访问有响应了之后执行的是把activity finish掉(回调也好,广播也好,反正就是把activity finish掉),那么恰好又是Thread1比Thread2快执行完毕,那么Thread2到了回调函数那里会不会有空指针之类的错误呢?

  • 写回答

1条回答 默认 最新

  • daweibalang717 2015-10-13 09:33
    关注

    package com.example.ab;

    import java.util.ArrayList;

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;

    public class MainActivity extends ActionBarActivity {

    private ArrayList<Integer> list;
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = new ArrayList<Integer>();
        new Thread(new Runnable() {
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (i <= 10) {
                    i++;
                    list.add(i);
                    Log.d("TAG", "aa = " + i);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Log.d("TAG", "finish");
                finish();
    
    
            }
        }).start();
    
    }
    
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }
    

    }

    日志:
    01-02 09:08:22.649: D/TAG(4925): aa = 1
    01-02 09:08:23.149: D/TAG(4925): aa = 2
    01-02 09:08:23.659: D/TAG(4925): aa = 3
    01-02 09:08:24.159: D/TAG(4925): aa = 4
    01-02 09:08:24.659: D/TAG(4925): aa = 5
    01-02 09:08:25.159: D/TAG(4925): aa = 6
    01-02 09:08:25.659: D/TAG(4925): aa = 7
    01-02 09:08:25.669: D/TAG(4925): finish
    01-02 09:08:25.679: D/TAG(4925): onDestroy
    01-02 09:08:26.159: D/TAG(4925): aa = 8
    01-02 09:08:26.659: D/TAG(4925): aa = 9
    01-02 09:08:27.159: D/TAG(4925): aa = 10
    01-02 09:08:27.659: D/TAG(4925): aa = 11

    评论

报告相同问题?