简体   繁体   中英

Is it a good practice to pass an object of Android Activity to a Thread class' constructor?

While writing an Android activity that submits input queries to a web server, I was thinking instead of having an anonymous inner class to define the networking thread, why can't we use a separate class that extends Thread.

While this works as expected, I would like to know whether this belongs any good or bad practice.

public class GreetActivity extends Activity{
    public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_greet_activity);
    }

    public void onClickBtn(View v){
         Thread t = new WorkerThread("http://10.0.2.2:8080",this);
         t.start();
    }
}

class WorkerThread extends Thread{
    private String targetURL;
    private Activity activity;

    public WorkerThread(String url, Activity act){
         this.activity = act;
         this.targetURL = url;
    }

    public void run(){
         TextView tv = (TextView) activity.findViewById(R.id.textview1);
         . . . . . . 
    }

}

在您的情况下,不是没有,因为只有UI Thread可以触摸UI,您的代码将使您的应用程序崩溃

android.view.ViewRoot$CalledFromWrongThreadException
  1. Passing an Activity reference to a thread has some caveats. Activity lifecycle is separate from thread lifecycle. Activities can be destroyed and recreated eg by orientation change events. If the activity reference is hold in a thread, the resources held by the activity (lots of bitmap assets for example, taking a lot of memory) are not garbage collectible.

    An non-static inner class also has the same problem since the reference to the parent is implicit.

    A working solution is to clear the activity reference when the activity is destroyed, and supply a new activity reference when the activity is recreated.

  2. You can only touch your UI widgets in the UI thread as mentioned by blackbelt.

For what it's worth, an AsyncTask is easier to work with than a bare-bones Thread .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM