Android中與對象相關聯的final引用變數建立

來源:互聯網
上載者:User
在看Android2.2
SDK源碼時,在MemoryFile.java中看到有這麼一段代碼:private final boolean mOwnsRegion;
// false if this is a ref to an existing ashmem region 其構造器為:    public MemoryFile(String name, int length) throws IOException
{
        mLength = length;
        mFD = native_open(name,
length);
        mAddress = native_mmap(mFD, length, PROT_READ |
PROT_WRITE);
        mOwnsRegion = true;
    } 一看這不是final麼,怎麼不在聲明的時候初始化呢?可能你這個時候會笑話,它這樣寫自然有這樣寫的道理。然後我在自己的一個Activity中也這樣聲明一個final變數,在onCreate方法中給它初始化,結果Eclipse立馬報錯,要我去掉final關鍵字。自己感覺有點奇怪,為什麼它可以這樣定義,而我就出錯呢?經過研究發現是對Activity的載入過程還不瞭解,準備寫代碼測試下直接上源碼:package
com.husttic.phone.Test;

import android.app.Activity;

public class
MyActivity extends Activity {
    class myThread extends Thread
{
        private int count3;

        public void run()
{
            while (true)
{
                h.sendEmptyMessage(HANDLER_TEST);
                Log.d(TAG,
"The worker thread id = "
                                +
Thread.currentThread().getId() +
"/tcount3="
                                +
count3);
                count3++;
                //
不能在此執行UI線程中View的重新整理
                //
mButton.setText("ID="+Thread.currentThread().getId()+"
count="+count);
                try
{
                    Thread.sleep(3000);
                } catch
(InterruptedException e) {
                    // TODO Auto-generated catch
block
                    e.printStackTrace();
                }
            }
        }
    }

    class
myThread2 extends Thread {
        private int count4;
        private
boolean flag = true;

        /**
         * @return the
flag
         */
        public synchronized final boolean isFlag()
{
            return flag;
        }

        public void run()
{
            while (this.flag)
{
                h.sendEmptyMessage(HANDLER_TEST);
                Log.d(TAG,
"The worker thread2 id = "
                                +
Thread.currentThread().getId() +
"/tcount4="
                                +
count4);
                count4++;
                try
{
                    Thread.sleep(100);
                } catch
(InterruptedException e) {
                    // TODO Auto-generated catch
block
                    e.printStackTrace();
                }
            }
            Log.d(TAG,
"The worker thread2 id = "
                    +
Thread.currentThread().getId() +
"/tENDING");
        }

        /**
         * @param
flag
         * the flag to set
         */
        public synchronized
final void setFlag(boolean flag) {
            this.flag =
flag;
        }
    }
    static final int HANDLER_TEST = 1;
    //
與類相關聯的static變數測試
    private static int sCount = 2;

    private static
final String TAG = "MyActivity";

    private static final String
TRAVE_VIEW = "TRAVE_VIEW";

    Handler h = new Handler()
{
        public void handleMessage(Message msg) {
            switch
(msg.what) {
            case HANDLER_TEST:
                Log.d(TAG,
"The handler thread id = "
                        +
Thread.currentThread().getId() + "/n");
                mButton.setText("ID="
+ Thread.currentThread().getId()
                        + " count=" +
count);
                break;
            }

        }
    };

    private
int count;

    private Button mButton;
    //
與對象相關聯的final變數測試
    private final boolean mFinalTest;

    private
Runnable mRunnable = new Runnable() {

        public void run()
{
            // 為了方便 查看,我們用Log列印出來
            Log.e(TAG,
Thread.currentThread().getName() + " " +
count);
            count++;
            setTitle("當前線程ID=" +
Thread.currentThread().getId() + " " + count);
            //
每2秒執行一次run方法
            h.postDelayed(mRunnable,
2000);
        }

    };
    private Runnable mRunnable2 = new
Runnable() {

        private int count2 = 0;

        public void
run() {
            mTextView.setText("當前線程ID=" +
Thread.currentThread().getId() + " "
                    +
count2);
            count2++;
            h.postDelayed(mRunnable2,
300);
        }

    };

    private TextView
mTextView;

    private myThread2 th;

    //
static代碼塊測試
    static {
        System.out.println("In Static
Block");
        MyActivity.sCount = 3;
    }

    //
構造器測試
    public MyActivity()
{
        super();
        System.out.println("In MyActivity
Method");
        this.mFinalTest =
true;
        System.out.println(this.mFinalTest);
        System.out.println(MyActivity.sCount);
    }

    @Override
    public
void finish() {
        Log.d(TAG, "in finish
Method");
        super.finish();
    }

    @Override
    public
boolean isFinishing() {
        Log.d(TAG, "in isFinishing
Method");
        return
super.isFinishing();
    }

    @Override
    public void
onConfigurationChanged(Configuration newConfig) {
        Log.d(TAG, "in
onConfigurationChanged Method");
        //
螢幕方向改變後重新擷取螢幕尺寸
        DisplayMetrics dm = new
DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        //
主動釋放對象引用
        dm =
null;
        super.onConfigurationChanged(newConfig);
    }

    /**
Called when the activity is first created. */
    @Override
    public
void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "in onCreate
Method");
        //下面這行代碼出錯
        //
this.mFinalTest=true;
        super.onCreate(savedInstanceState);
        //用於方法跟蹤分析
        Debug.startMethodTracing(TRAVE_VIEW);
        Log.d(TAG,
"The main thread id = " + Thread.currentThread().getId()
                +
"/n");

        setContentView(R.layout.main);
        mTextView =
(TextView) this.findViewById(R.id.textView1);
        this.mButton = (Button)
this.findViewById(R.id.button1);
        this.mButton.setOnClickListener(new
OnClickListener() {

            @Override
            public void
onClick(View v) {
                // TODO Auto-generated method
stub
                th.setFlag(false);
                //測試構造器
                new
MyActivity();
            }

        });
        //
通過Handler啟動線程
        h.post(mRunnable);
        h.post(mRunnable2);

        //
此線程無法再引用(回收不了)
        new
myThread().start();

        //可再引用
        th = new
myThread2();
        th.start();
    }

    @Override
    public
void onDestroy() {
        Log.d(TAG, "in onDestroy
Method");
        h.removeCallbacks(this.mRunnable);
        h.removeCallbacks(this.mRunnable2);
        super.onDestroy();
    }

    @Override
    public
void onPause() {
        Log.d(TAG, "in onPause
Method");
        super.onPause();
    }

    @Override
    public
void onPostCreate(Bundle savedInstanceState) {
        Log.d(TAG, "in
onPostCreate
Method");
        super.onPostCreate(savedInstanceState);
    }

    @Override
    public
void onPostResume() {
        Log.d(TAG, "in
onPostResume");
        super.onPostResume();
    }

    @Override
    public
void onRestart() {
        Log.d(TAG, "in onRestart
Method");
        h.post(mRunnable);
        h.post(mRunnable2);
        super.onRestart();
    }

    @Override
    public
void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.d(TAG,
"in onRestoreInstanceState
Method");
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public
void onResume() {
        Log.d(TAG, "in onResume
Method");
        super.onResume();
    }

    @Override
    public
void onSaveInstanceState(Bundle outState) {
        Log.d(TAG, "in
onSaveInstanceState
Method");
        super.onSaveInstanceState(outState);
    }

    @Override
    public
void onStart() {
        Log.d(TAG, "in onStart
Method");
        super.onStart();
    }

    @Override
    public
void onStop() {
        Log.d(TAG, "in onStop
method");
        h.removeCallbacks(this.mRunnable);
        h.removeCallbacks(this.mRunnable2);
        Debug.stopMethodTracing();
        super.onStop();
    }
} 這個測試了Activity的各個狀態,以及UI線程和其他線程之間資訊交流的橋樑Handler這個類還存在一個問題,在退出Activity之後,其他線程還在執行~很奇怪吧,可以開啟LogCat看下,一直在列印資訊呢。所以Android裡麵線程的使用還是注意點為好~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.