日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android?Handler消息傳遞機制_Android

作者:上后左愛 ? 更新時間: 2023-01-17 編程語言

Handler 消息傳遞機制

Android中每一個應用就是一個進程,Handler消息傳遞機制 利用JAVA中多線程的概念,比如在主界面 就是UI主線程,同時在UI界面中某個框內消息晃動就是子線程。

機制: Android中子線程不能操作主線程組件 但是場景: 必須在子線程中更新主線程的UI組件,比如下載的進度條顯示,子線程復雜下載,但是告訴主線程下載進度條 所以可以使用Handler機制

作用:

1. 在任意的線程中發送消息

2. 在主線程中獲取并且 處理消息

// 如何使用Handler周期性的更新消息,比如進度條
package com.example.myapplication;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
// 從手機的通訊錄中獲取信息
public class MainActivity extends AppCompatActivity {
    final int TIME = 60;    //定義時間長度
    final int TIMER_MSG = 0x001;    //定義消息代碼
    private ProgressBar timer;    //聲明水平進度條
    private int mProgressStatus = 0;    //定義完成進度
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timer = (ProgressBar) findViewById(R.id.timer);
        // 3. 啟動進度條
        handler.sendEmptyMessage(TIMER_MSG);
    }
    //創建Handler對象實現1秒中更新一次進度
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(TIME - mProgressStatus > 0){
                mProgressStatus +=1;
                timer.setProgress(TIME-mProgressStatus);
                // 通過消息代碼進行子線程識別
                handler.sendEmptyMessageDelayed(TIMER_MSG,1000);
            }else{
                Toast.makeText(MainActivity.this, "時間到!游戲結束!", Toast.LENGTH_SHORT).show();         //提示時間已到
            }
        }
    };
}

Handler Looper MessageQueue關系

Handler 與Looper 中MessageQueue 之間通過Message進行交互

Message是Handler 與Looper 之間交互的橋梁

Message: 對象屬性 :

1. Int 整形

2.obj Object類型

3.replyTo 發送到何處 what 自定義的

Message.Obatin()

Handler.obtainMessage() 實現 這兩個對象避免創造多余對象 導致對象的消息 Message 對象可以循環利用

package com.example.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ViewFlipper;
import androidx.appcompat.app.AppCompatActivity;
// 從手機的通訊錄中獲取信息
public class MainActivity extends AppCompatActivity {
    final int FLAG_MSG = 0x001;    //定義要發送的消息代碼
    private ViewFlipper flipper;   //定義ViewFlipper
    private Message message;        //聲明消息對象
    //定義圖片數組
    private int[] images = new int[]{R.drawable.img1, R.drawable.img2, R.drawable.img3,
            R.drawable.img4, R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8};
    private Animation[] animation = new Animation[2];  //定義動畫數組,為ViewFlipper指定切換動畫
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        flipper = (ViewFlipper) findViewById(R.id.viewFlipper);  //獲取ViewFlipper
        for (int i = 0; i < images.length; i++) {      //遍歷圖片數組中的圖片
            ImageView imageView = new ImageView(this);  //創建ImageView對象
            imageView.setImageResource(images[i]);  //將遍歷的圖片保存在ImageView中
            flipper.addView(imageView);             //加載圖片
        }
        //初始化動畫數組
        animation[0] = AnimationUtils.loadAnimation(this, R.anim.slide_in_right); //右側平移進入動畫
        animation[1] = AnimationUtils.loadAnimation(this, R.anim.slide_out_left); //左側平移退出動畫
        flipper.setInAnimation(animation[0]);   //為flipper設置圖片進入動畫效果
        flipper.setOutAnimation(animation[1]);  //為flipper設置圖片退出動畫效果
        // 開啟廣告輪播 主線程中
        message = Message.obtain();
        message.what = FLAG_MSG;
        handler.sendMessage(message);
    }
    //創建Handler對象實現1秒中更新一次進度
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FLAG_MSG) {
                flipper.showPrevious();                  //示下一張圖片
            }
            message = handler.obtainMessage(FLAG_MSG);   //獲取要發送的消息
            handler.sendMessageDelayed(message, 3000);  //延遲3秒發送消息
        }
    };
}

Looper 使用

Handler 在主線程中創建 自動幫我們創建Looper對象

如果在子線程中創建 Handler 中 LooperThread

1. 子線程中創造Handler

2. 初始化Looper對象 Looper.prepare()

3.new Handler()

4.looper.loop

package com.example.myapplication;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
public class LooperThread extends Thread {
    public Handler handler;					//聲明一個Handler對象
    @Override
    public void run() {
        super.run();
        //初始化Looper對象
        Looper.prepare();
        //實例化一個Handler對象
        handler = new Handler() {
            public void handleMessage(Message msg) {
                Log.i("Looper", String.valueOf(msg.what));
            }
        };
        Message m=handler.obtainMessage();	//獲取一個消息
        m.what=0x7;						//設置Message的what屬性的值
        handler.sendMessage(m);			//發送消息
        Looper.loop();						//啟動Looper
    }
}

原文鏈接:https://blog.csdn.net/qq_27217017/article/details/107301153

欄目分類
最近更新