I have 3 threads : UI Thread
(MainActity thread), Thread1
and Thread2
. UI Thread
starts Thread1
and Thread1
starts Thread2
There is a MainActity class variable that I want to instantiate. What I did was using MainActivity.this.runOnUiThread(new Runnable() {...}
to instantiate a TextView
from a broadcastReceiver. But I thought that Thread2
would have the new value of that text view. It does not. It still has the initial value (ie before the private boradcastreceiver alters it. How can I get the new value in Thread2
?
Below is how my code looks like :
public class MainActivity extends AppCompatActivity {
TextView mytxtView; //Use to bind a TextView from UI layout
@Override
protected void onCreate(Bundle savedInstanceState) {
mytxtView = (TextView) findViewById(R.id.mytxtView);
mytxtView.setText("Value 1");
Thread thread1 = new Thread(new Thread1());
thread1.start();
}
public void onResume() {
registerReceiver(myReceiver, new IntentFilter("android.provider.Telephony.SOME_TELEPHONY_INTENT_ACTION"))
}
private class Thread1 extends Thread{
@Override
public void run() {
Thread thread2 = new Thread(new Thread2());
thread2.start();
}
}
private class Thread2 extends Thread{
@Override
public void run() {
Thread.sleep(45000) ; //just to make sur myReceiver does its job
Toast.makeText(getApplicationContext(),myTxtView.getText(),Toast.LENGTH_LONG).show();
// This shows "Value 1" instead of "Value 2"
}
}
BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().
equals("android.provider.Telephony.SOME_TELEPHONY_INTENT_ACTION")){
//do some work
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
myTxtView.setText("Value 2");
}
}}
}
Issue : your are just registering your broadcast but your are never triggering it so you need to trigger the broadcast to to execute onReceive
method using sendBroadcast(yourBroadcastIntent).
Try
public void onResume() {
registerReceiver(myReceiver, new IntentFilter("android.provider.Telephony.SOME_TELEPHONY_INTENT_ACTION"));
sendBroadcast(new Intent(""android.provider.Telephony.SOME_TELEPHONY_INTENT_ACTION""));
}
And no need of runOnUiThread
in receiver , as @greenapps has already mentioned it as well
And it setText
to set the text as
myTxtView.setText("Value 2");
though seems like a typo info.myTxtView("Value 2");
Update : Working Project files repo
along with screenshot to demonstrate the working state with provided screenshot.
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.