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);
}
};