1

Hi I am new to android programming and I was having some issues in application initialization. I will explain app structure first and then problems.

The application has a thread which should always run and listen on Datagram socket. Whenever a message is received it takes appropriate actions. On certain actions I needed Context object and I also use Handler object for passing data to UI thread. Both of these objects were initialized in my Thread class's constructor by passing from main activity's OnCreate method. Now I am having the problem that whenever my activity is switched or I tilt the phone, all objects in main activity are recreated and the references which I passed before to Thread class of Handler and Context becomes invalid.

How should I handle this problem. Thanks in advance. Application structure is like this.

public class MainActivity extends Activity {
    private Context ctx;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String mtype = bundle.getString("mtype");

            // DO SOME STUFF HERE //

        }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // OTHER INITIALIZATIONS //

        ctx = this;
        rxThread = new ControlReceiver(ctx, handler);
        rxThread.start();

    }
};

The thread class is like this.

public class ControlReceiver extends Thread {
    private Context context;
    private Handler handler;


    ControlReceiver(Context c, Handler h){
        context = c;
        handler = h;
    }

    public void run() {

        // DO STUFF HERE //

        // SEND MESSAGE TO UI //
        msg = handler.obtainMessage();
        bundle = new Bundle();
        bundle.putString("mtype", "ECHTB");
        msg.setData(bundle);
        handler.sendMessage(msg);

    }
};
Kanwar Saad
  • 2,138
  • 2
  • 21
  • 27

2 Answers2

1

There seems to be two school for managing objects that have an application lifecycle:

  • singleton
  • application objects

Here's the so topic about it : Singletons vs. Application Context in Android?

I think it mainly depends on the use case and in your particular code sample I would favor the creation of a singleton which would keep the controlreceiver alive and available to any activity (to be more precise, the singleton would manage the lifecycle of the controlreceiver).

Community
  • 1
  • 1
Gomoku7
  • 1,362
  • 13
  • 31
  • 1
    by the way, do not use local context for initialising the controlreceiver, use application context. Explained here : http://stackoverflow.com/questions/7298731/when-to-call-activity-context-or-application-context – Gomoku7 Jun 11 '13 at 10:58
  • Singleton is ok, but it has a risk...your singleton class could be destroyed by the garbage collector, and your saved data could be lost. – Fustigador Jun 11 '13 at 11:00
  • I've never seen a singleton being gc (or it's not properly coded). could you provide source or code ? ... just made a search in so : http://stackoverflow.com/questions/453023/are-static-fields-open-for-garbage-collection – Gomoku7 Jun 11 '13 at 11:09
0

my two ways to avoid objects recreation on phone rotation: 1) force the orientation (vertical/horizontal) in the manifest for that activity

<activity
android:name=".MainMenu"
android:screenOrientation="portrait" >
</activity>

2) manage the orientation, in the manifest declaring your activity will take care of changes

<activity
android:name=".tools.ToolGPSRecorder"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="sensor" >
</activity>

in this case, in the activity the event onConfigurationChanged will be fired whire rotating the phone, in this event you will load a layout, that could be a specific layout-land one.

i.e.
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    MyLog.d("ToolGPSRecorder.onConfigurationChanged");
    setContentView(R.layout.tool_gpsrecorder);
    ResetTimersAndLogs();
    ShowCoveredDistance();
    UpdateRecordingTime();
    ...
edestrero
  • 516
  • 6
  • 5
  • hmm .. nice . but it won't work in my case. I need a general solution not only specific to orientation change. – Kanwar Saad Jun 11 '13 at 10:24
  • Have you used the savedInstanceState Bundle of the onCreate method? That Bundle is there to save the state of the Activity in case it is closed. You can see an example in this link: http://stackoverflow.com/questions/151777/saving-activity-state-in-android – Fustigador Jun 11 '13 at 10:33
  • hello Fustigador, I had to keep too much data "alive" to use bundles, my code suits well for my needs, thanks :) – edestrero Jun 11 '13 at 12:24