Android在BroadcastReceiver中通过接口回调更新界面

来源:互联网 发布:数据库创建索引规则 编辑:程序博客网 时间:2024/06/08 09:06

之前写广播接收器都是写在Activity的内部的,觉得看起来很乱的感觉,毕竟广播也事和活动是同一级别的组件之一,哪儿能放在活动的里面啊,决定就来封装一下,发现居然没有思路,,同事说用静态类,直接点就可以了,

但是静态类在内存中不会被回收,只有等程序结束后才会回收,所以决定用接口回调接口回调在安卓中用的很多吧,这个不懂的可以自行搜索一下哈,就不普及基础了,
  1. 新建一个接口UpdateUIListenner.class
public interface UpdateUIListenner {    /**     * 更新UI     */    void UpdateUI(String str);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 新建一个BroadcastReceiver取名 MyReceiver
public class MyReceiver extends BroadcastReceiver {    UpdateUIListenner updateUIListenner;    @Override    public void onReceive(Context context, Intent intent) {        String key = intent.getStringExtra("key");        updateUIListenner.UpdateUI(key);    }    /**     * 监听广播接收器的接收到的数据     * @param updateUIListenner     */    public void SetOnUpdateUIListenner(UpdateUIListenner updateUIListenner) {        this.updateUIListenner = updateUIListenner;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  1. 在MainActivity里面
public class MainActivity extends AppCompatActivity {    MyReceiver myReceiver;    TextView tv1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button btn = (Button) findViewById(R.id.btnSend);        tv1 = (TextView) findViewById(R.id.tv);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //发送广播                Intent intent = new Intent();                intent.putExtra("key", "数据数据");                intent.setAction("gengxin");                sendBroadcast(intent);                Log.e("+++++","发送广播");            }        });        //注册广播  ------接口回调不能使用静态注册,只能动态注册        myReceiver = new MyReceiver();        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction("gengxin");        registerReceiver(myReceiver, intentFilter);        myReceiver.SetOnUpdateUIListenner(new UpdateUIListenner() {            @Override            public void UpdateUI(String str) {                tv1.setText(str);            }        });    }    @Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(myReceiver);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

源码下载(Android Studio)

0 0
原创粉丝点击