簡體   English   中英

Android活動創建我的線程的多個實例

[英]android activity create multiple instance of my thread

我需要檢查變量以進行更改,如果更改發生,我將更新textview。

所以我為此創建了一個帶有while循環的新線程。 我通過Thread.sleep()每1秒檢查一次變量

此線程在onCreate()中創建並啟動。 所以是一次

問題是每次我翻轉手機(從垂直到水平或...)時,都會創建一個新線程。

這是我的代碼:

public class HomeActivity extends Activity
{
private final static int LOAD_SUCCESSFULL = 1;
private final long LOCATION_THREAD_SLEEP = 1000;    
private boolean flag = false;   
static TextView lat;
static TextView lon;    
static Location currentLocation = null; 
Thread locationThread;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);        
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.new_home2);
    this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.new_home_titlebar);

    lat = (TextView)findViewById(R.id.t2rt3);
    lon = (TextView)findViewById(R.id.t2rt4);

    /* FindLocation class is a helper class that find location via simcard or gps in separate thread,
        same problem happen with this thread also, it create multiple thread, for ease of work i 
        commented this part.
    */      
    //FindLocation fn = new FindLocation(this);

    locationThread = new Thread(null, loadLocation, "loadLocationHomePage");

    locationUpdater();
}

private static Handler locationUpdateHandler = new Handler()
{
    public void handleMessage(Message msg)
    {
        switch(msg.what)
        {
        case LOAD_SUCCESSFULL:
            lat.setText(Double.toString(currentLocation.getLatitude()));
            lon.setText(Double.toString(currentLocation.getLongitude()));
            //stopThread();
            break;              
        }
    }
};

private Runnable loadLocation = new Runnable()
{
    public void run()
    {
        //boolean flag = false;
        while(!flag)
        {
            if(Data.currLocation != null)
            {                   
                currentLocation = new Location(Data.currLocation);                  
                Message msg = locationUpdateHandler.obtainMessage(LOAD_SUCCESSFULL);                    
                locationUpdateHandler.sendMessage(msg); 
                //return;
                flag = true;
                //return;
            }               
            else
            {
                try 
                {
                    Thread.sleep(LOCATION_THREAD_SLEEP);
                } 
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }               
        }
    }
};

public void locationUpdater()
{
    //Thread locationThread = new Thread(null, loadLocation, "loadLocationHomePage");
    locationThread.start();
}

那么我該如何解決呢?

在此處輸入圖片說明

實際上,問題在於,每當您翻轉手機時,都會創建一個Activity的新實例,因此,您每次旋轉都會在onCreate()上調用一次,在該位置上您會盲目地創建一個新Thread並啟動新Thread

這是每個Activity的默認行為,但我們可以通過在AndroidManifest文件中為Activity聲明一個屬性來更改Activity的重新創建

<activity
    android:name="yourPackage.ActivityName"
    android:configChanges="keyboardHidden|orientation|screenSize"
</activity>

這將防止在方向更改時創建“活動”。

如果您override這些定向事件,

@Override
        public void onConfigurationChanged(Configuration newConfig) {}

希望這將解決此問題,而無需實現可能在其他一些用例中破壞的復雜邏輯。

我認為您可能並沒有以最有效的方式進行此操作。

但是,如果您的問題很簡單,我如何防止產生多個工作線程,則應查看無UI片段。

http://www.vogella.com/articles/AndroidFragments/article.html#headlessfragments1

我不知道為什么Android會這樣做。 如果我將代碼放在onResume()中,則此行為有意義,但就我而言,我不知道。

無論如何,我發現了一個骯臟的解決方案。 這個想法是找到所有線程的列表並搜索他們的線程,如果存在則阻止創建另一個線程。

public boolean checkThreadExist()
{
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for(int i = 0; i < threadArray.length ; i++)
    {
        if(threadArray[i].getName().equalsIgnoreCase("loadLocationHomePage"))
            return true;
    }

    return false;
}

更新了onCreate():

if(checkThreadExist())
    {

    }
    else
    {
        locationThread = new Thread(null, loadLocation, "loadLocationHomePage");            
        locationUpdater();            
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM