简体   繁体   中英

Pass data from thread to activity

In my application I have an activity that starts a thread

connectThread = new ConnectThread(MainActivity.this , device);
connectThread.start();

in this thread 2 things are done : 1. a new thread is created 2. and a new activity is started

connectedThread = new ConnectedThread(mmSocket);
connectedThread.start();

    handler.post(new Runnable() {

        @Override
        public void run() {
            MainActivity.connectingProgressBar.setVisibility(View.GONE);

            Intent startPostGet = new Intent(context, PostGetActivity.class);
            startPostGet.putExtra(MainActivity.EXTRA_DEVICE, mmDevice);
            context.startActivity(startPostGet);                
        }
    });

in the latest created thread (connectedthread) I receive data and want to pass this to the newest activity (postgetactivity)

i was thinking about doing something like this in the connectedthread:

handler.post(new Runnable() {
        @Override
        public void run() {
            PostGetActivity.statusTextView.setText("Got data");
            PostGetActivity.processData(data)
        }
    });

The problem is that the function processData() may not be static but I am referencing it from a static context.

How can I fix this? Any help will be appreciated.

You can force your handler to post to the main thread as so:

Handler mainHandler = new Handler(getMainLooper());

All UI operations need to be on the main thread, so since you are calling them from a thread you created you need to do that.

Secondly, you need to pass data to the new activity in the Intent object as you have done earlier.

Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("KEY", "String data");
startActivity(intent);

The main thing is, your handler should post the runnable to the main thread (As shown above).

Do this in connectedthread . Using FLAG_ACTIVITY_SINGLE_TOP won't restart your activity but a specific callback onNewIntent will be called

Intent i = new Intent(context, PostGetActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("data", "data_from_thread");
context.startActivity(i);

You can get data in PostGetActivity like this

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String data = intent.getStringExtra("data"); // you will get "data_from_thread"
    // use this string the way you want
}

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