Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid Application Init and global objects
    primarykey
    data
    text
    <p>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.</p> <p>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 <strong>Context</strong> object and I also use <strong>Handler</strong> 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 <strong>OnCreate</strong> 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 <strong>Handler</strong> and <strong>Context</strong> becomes invalid.</p> <p>How should I handle this problem. Thanks in advance. Application structure is like this.</p> <pre><code>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(); } }; </code></pre> <p>The thread class is like this.</p> <pre><code>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); } }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload