xulinliang99
xulinliang99
2019-03-30 15:52

使用Handler+计数器Timer 跨类传递消息时消息收不到,而不用Timer就可以,为什么。

  • android

MainActivity.java

public class MainActivity extends Activity {
     @SuppressLint("HandlerLeak")
     static Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.d("HandlerMSG","fromMain:"+msg.what);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Timer timer=new Timer();
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                Message message=Message.obtain();
                message.what=1;
                handler.sendMessage(message);
                Message message1=Message.obtain();
                message1.what=2;
                MyHandler.handler.sendMessage(message1);
            }
        };
        timer.schedule(timerTask,0,2000);

        Button button=findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,Main2Activity.class));
            }
        });
    }
}

Main2Activity.java

public class Main2Activity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message=Message.obtain();
                message.what=3;
                MainActivity.handler.sendMessage(message);
                Message message1=Message.obtain();
                message1.what=4;
                MyHandler.handler.sendMessage(message1);
            }
        });
    }
}

MyHandler.java

public class MyHandler {
    @SuppressLint("HandlerLeak")
    static Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.d("!!!@", "FromMyHandler:"+msg.what);
        }
    };
}

在Main1中使用定时器向Main的handler和MyHandler的handler传递一个消息,测试时使用点击事件可以传递,而使用定时器就不可以向MyHandler的handler传递消息了,而在Main2中希望通过点击事件也向两个Handler传递消息,测试发现如果Main中写了定时器向MyHandler发送消息后,Main2也不能向MyHandler发消息,猜测是不是定时器堵塞了Myhandler的类中handler??

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

0条回答