handler弱引用方式

package com.example.handler;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.lang.ref.WeakReference;

public class MainActivity extends AppCompatActivity {


    private Handler handler;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.btn);

        handler=new MyHandler(this);



        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    handler.sendEmptyMessage(0);
            }
        });



    }
    private static class MyHandler extends  Handler{
        WeakReference  weakReference;
        Context context;
        public MyHandler(MainActivity activity){
            context=activity;
          weakReference =new WeakReference(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(weakReference.get()!=null){
                if(msg.what==0){
                    Toast.makeText(context,"调用",Toast.LENGTH_LONG).show();
                }
            }
        }


    }
}

你可能感兴趣的:(handler弱引用方式)