我有3个线程:UI Thread(MainActity线程),Thread1Thread2
UI Thread启动Thread1Thread1启动Thread2

我想实例化一个MainActity类变量。我所做的是使用MainActivity.this.runOnUiThread(new Runnable() {...}实例化来自broadcastReceiver的TextView。但是我认为Thread2具有该文本视图的新价值。它不是。它仍然具有初始值(即在私有boradcastreceiver对其进行更改之前。如何在Thread2中获取新值?

以下是我的代码:

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

最佳答案

问题:您只是在注册广播,但从未触发它,因此您需要触发广播才能使用onReceive执行sendBroadcast(yourBroadcastIntent).方法

尝试

public void onResume() {
    registerReceiver(myReceiver, new IntentFilter("android.provider.Telephony.SOME_TELEPHONY_INTENT_ACTION"));
    sendBroadcast(new Intent(""android.provider.Telephony.SOME_TELEPHONY_INTENT_ACTION""));
   }


并且在接收器中不需要runOnUiThread,因为@greenapps也已经提到了它

并且setText将文本设置为

myTxtView.setText("Value 2");


虽然看起来像是错字info.myTxtView("Value 2");

更新:Working Project files repo和屏幕快照,以使用提供的屏幕快照演示工作状态。

关于java - 将数据从broadcastreceiver发送到android中的自定义线程不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47112154/

10-10 11:06