在使用Broadcast 时我们应该注意到,BroadcastReceiver的子类别都是无状态的类别,每次收到发送广播事件后,BroadcastReceiver都会创建一个新的对象,然后再执行onReceive()函数,当onReceive()函数执行完毕后,就立刻删掉该对象,下一次再收到此广播后,又会创建一个新的对象。所以说Broadcast组建是Android中最轻薄、最短小的组建。我们把上一篇文章的代码稍作一下修改,增加了一个static的变量numStatic ,和num变量 。代码如下:
- /**
- * Broadcaster.java
- * com.androidtest.broadcaster
- *
- * Function: TODO
- *
- * ver date author
- * ──────────────────────────────────
- * 2011-6-9 Leon
- *
- * Copyright (c) 2011, TNT All Rights Reserved.
- */
- package com.androidtest.broadcaster;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
- /**
- * ClassName:Broadcaster
- * Function: TODO ADD FUNCTION
- * Reason: TODO ADD REASON
- *
- * @author Leon
- * @version
- * @since Ver 1.1
- * @Date 2011-6-9
- */
- public class Broadcaster extends BroadcastReceiver{
- private static final String TAG = "Broadcaster";
- private static int numStatic =100 ;
- private int num =100 ;
- @Override
- public void onReceive(Context context, Intent intent) {
- // TODO Auto-generated method stub
- String string = intent.getAction();
- numStaticnumStatic= numStatic+50;
- num=100+50;
- Log.v(TAG , "The action is "+ string + "Static Number is :" + numStatic
- + " Object num is :" + num);
- }
- }
多次发送广播,然后输出的结果如下,我们可以看到static Number 每次执行都会增加,而Object Num因为每次都要创建所以一直都是一个固定的值。
本文转自 最牛傻蛋 51CTO博客,原文链接:http://blog.51cto.com/zuiniuwang/718288,如需转载请自行联系原作者