• Android开发--线程间通信


    参考:简书文章

    今天作业是关于线程间通信,线程间通信有好几种方式,本次使用Handler机制,其他日后补充。

    题目:准备五张图片, 随着子线程的变化,图片和计数器会进行有规律的变化。如图:

     

    package com.zzu.jiaoyanyan.animation;
    
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
        ImageView imageView;
        TextView all;
        TextView index;
        Handler handler;
        ArrayList<Integer> image;
        Runnable myRunnable1;
        int count, total;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            imageView = findViewById(R.id.imageView);
            all = findViewById(R.id.textView3);
            index = findViewById(R.id.textView4);
    
            image = new ArrayList<>();
            image.add(R.drawable.animation1);
            image.add(R.drawable.animation2);
            image.add(R.drawable.animation3);
            image.add(R.drawable.animation4);
            image.add(R.drawable.animation5);
    
            handler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    int i = total % 5;
                    total += 1;
                    imageView.setImageResource(image.get(i));
    
                    all.setText(""+ total);//????奇怪的东西出现了
                    count = i+1;
                    index.setText(" "+count);
                }
            };
    
             myRunnable1= new Runnable() {
                @Override
                public void run() {
                    while (true){
                        Log.d("TAG", "I am Sub Thread.");
                        Message message = new Message();
                        handler.sendMessage(message);
                        try {
                            Thread.sleep(800);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                }
            };
    
            Thread t = new Thread(myRunnable1);
            t.start();
    
        }
    
    }
    Today And Next
  • 相关阅读:
    在HTML中使用JavaScript
    七层网络模型
    JS执行机制
    继承
    变量作用域
    跨域
    ES6-Promise
    回调函数
    2019.3.9笔试
    CSS3新特性
  • 原文地址:https://www.cnblogs.com/yayyer/p/12342870.html
Copyright © 2020-2023  润新知