• 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
  • 相关阅读:
    爬虫工具简单整理
    vue单页面处理SEO问题
    深入浅出MyBatis-快速入门
    js的匿名函数 和普通函数
    Javascript位置 body之前、后执行顺序!
    eclipse中的ctrl+H使用中的问题
    Eclipse中ctrl+shift+r与ctrl+shift+t的区别
    Java 判断字符串是否为空的四种方法、优缺点与注意事项
    eclipse 快捷键
    只缩进新加一段代码的方法
  • 原文地址:https://www.cnblogs.com/yayyer/p/12342870.html
Copyright © 2020-2023  润新知